﻿using ControllerClient.Bean;
using ControllerClient.cmdinfo;
using ControllerClient.datainfo;

using ICCardHelper;
using Newtonsoft.Json.Linq;
using PCSC.Monitoring;
using Pg.Rfid;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Newtonsoft.Json;
//using HandheldHelper;
using System.Net;
using Newtonsoft.Json.Serialization;
using ControllerClient.Tools;
using Ini.Net;
using System.Text.RegularExpressions;
using System.IO.Ports;
using System.Collections.Specialized;
//using Ini.Net;
using CMBFingerPrint.Enums;
using CMBFingerPrint;
using System.Drawing.Imaging;
using System.Linq;
using System.Collections;
using System.Web.UI.WebControls;
using Midapex.Net.Ftp;
using Midapex.Net;

using Image = System.Drawing.Image;

namespace ControllerClient
{
    public partial class Form1 : Form
    {
        string cmdFilePath = "cmdfile";
        string comName = "COM1";
        SoundPlayer sound = null;

        public delegate void mFileChangeEventHandler(String cmdfilename);
        mFileChangeEventHandler fileChangeEventHandler;
        bool mjflag = false;
        //待办标识
        bool toDealFlag = false;
        PCSCReader readerPCSC = null;
        PCSCReader readerIC = null;
        socketClient socketClientMJ = null;

        Reader readerMJ = null;
        //入库
        EnterScanData esd = null;
        List<enterScanPackInfo> epcReal = null;
        EnterScanCMD esc = null;
        //扫描
        SuperScanData ssd = null;
        List<superScanPackinfo> ssdList = null;
        //出库
        OutScanData osd = null;
        List<transferData> epcOut = null;
        OutScanCMD osc = null;
        //实物交接
        TransferTransferData ttd = null;
        List<transferPackInfo> epcHandover = null;
        //电子签封入库核对
        CheckInData cidd = null;
        List<packInfoCheck> packInfoCheckList = null;
        //空电子签封入库
        EmptyPackCheckInData epcid = null;
        List<emptyPackInfo> emptyPackInfoList = null;
        EmptyPackCheckInCMD epcic = null;
        VerifyLicense vl = null;
        BaseCommand bc = null;
        Dictionary<string, string> sackMap = new Dictionary<string, string>();
        delegate void ChangeInvoke(string num);
        //public delegate void AutoCommit();
        //public event AutoCommit PDACommitEvent;
        //数据交换
        public delegate void APDUHandler(string APDUData);
        public delegate void HardwareInitializeHandler(string data);
        //电源管理8001
        public delegate void PowerManagerHandler(string data);
        //错误反馈1002
        public delegate void ErrorFeedbackHandler(string data);

        //检查环境1004
        public delegate void CheckEnvironmentHandler(string data);
        //接入1005
        public delegate void JoinUpHandler(string data);
        //下发2002
        public delegate void DownCommondHandler(string data);
        //命令2001
        public delegate void CommondHandler(string data);
        //执行2003
        public delegate void ExecuteHandler(string data);
        //确认2004
        public delegate void ConfirmHandler(string data);
        //元数据同步2005
        public delegate void UserDataSyncHandler(string data);
        //授权进出安全区域4003
        public delegate void AuthorizedAccessHandler(byte[] data);

        static TXTHelper ltUserInfo = new TXTHelper("UserInfo");
        static TXTHelper ltTaskCmd = new TXTHelper("TaskCmd");
        static TXTHelper ltTaskData = new TXTHelper("TaskData");
        static TXTHelper ltMetamark = new TXTHelper("Metamark");
        static TXTHelper ltid = new TXTHelper("id");
        //TXTHelper ltDayDiff = new TXTHelper("dayDiff.ini", 1);
        TXTHelper ltTimeDiff = new TXTHelper("timeDiff.ini", 1);
        TXTHelper ltScreen = null;
        TXTHelper ltScreenInfo = null;
        TXTHelper ltTaskInfo = null;
        TXTHelper taskCmdMaker = null;

        string taskIdSend;
        string greenOff = "0105000100009C0A ";
        string greenOn = "01050001FF00DDFA ";
        //on  0105000200006C0A
        string yellowOff = "0105000200006C0A";
        //off 01050002FF002DFA
        string yellowOn = "01050002FF002DFA";
        string redOff = "010500000000CDCA";
        string redOn = "01050000FF008C3A";
        //四号口
        string gateOn = "01050003FF007C3A";
        string gateOff = "0105000300003DCA";
        string gateOn1 = "01050004FF00CDFB";
        string gateOff1 = "0105000400008C0B";
        //6号口
        string gateOn2 = "01050005FF009C3B";
        string gateOff2 = "010500050000DDCB";
        //7号口
        string gateOn3 = "01050006FF006C3B";
        string gateOff3 = "0105000600002DCB";
        HashSet<string> cardHash1 = new HashSet<string>();
        HashSet<string> cardHash2 = new HashSet<string>();
        HashSet<string> cardHash3 = new HashSet<string>();
        static string operatorUser = "";
        static string auditorUser = "";
        string PSAMReaderName = "";
        string ICReaderName = "";
        string userGate = "";
        string userInfo = "";
        string userLogin = "";
        int userGateCount = 0;
        string mustSackNo = "";
        string stackCode = "";
        string stackName = "";
        //日志保留天数
        int logDays = 15;
        string controlId = "1001";
        string sequence = "";
        string dataToPDAFinal = "";
        //收到2002任务开启门架标识
        bool flagMJ = false;
        bool heartStatu = false;
        //栅栏门已开启标识，未开启则出入库业务不提交
        bool flagUser = false;
        //用户已登陆标识，未登陆则不启动门架
        bool flagLoginUser = false;
        //刷卡开启栅栏门标识
        bool flagGate = false;
        //用户刷完三张卡标识
        bool flagCard = false;
        //收到2005后提示用户登陆标识
        bool flagPrompt = false;
        bool flagEncry = false;
        bool debugButton = false;
        //人脸有效标识
        bool flagFace = false;

        //默认用户是否自动登陆
        bool loginUser = false;
        //用户刷卡解除经警报
        bool flagAlarm = false;
        //判断是否是必出箱
        bool mustOutSack = false;
        HashSet<string> epcList = new HashSet<string>();
        HashSet<string> notScanList = new HashSet<string>();
        //锁状态异常
        HashSet<string> errorList = new HashSet<string>();
        //不在任务列表
        HashSet<string> notTaskList = new HashSet<string>();
        List<ToDoTask> taskList = new List<ToDoTask>();
        List<string> userList = new List<string>();
        //实际已扫描款包
        string epcDataResult = "";
        string ServerIP = "";
        int port = 50003;
        //是否启用人脸设备
        bool faceUseing = false;
        bool heartStart = false;
        //用户刷卡卡号
        string cardAll = "";
        int openGateType = 2;
        NameValueCollection myCol = new NameValueCollection();
        private Int32 m_lUserID = -1;
        private Int32[] m_lAlarmHandle = new Int32[200];

        private int iDeviceNumber = 0; //添加设备个数
        private int iFileNumber = 0; //保存的文件个数
        private uint iLastErr = 0;
        private string strErr;
        int gateTime = 0;
        HashSet<string> cardHash = new HashSet<string>();
        HashSet<string> cardUserHash = new HashSet<string>();
        HashSet<string> cardLoginHash = new HashSet<string>();
        Dictionary<string, long> timerHash = new Dictionary<string, long>();

        public CHCNetSDK.LOGINRESULTCALLBACK LoginCallBack = null;
        private CHCNetSDK.EXCEPYIONCALLBACK m_fExceptionCB = null;
        private CHCNetSDK.MSGCallBack_V31 m_falarmData_V31 = null;
        public delegate void UpdateTextStatusCallback(string strLogStatus, IntPtr lpDeviceInfo);
        public delegate void UpdateListBoxCallback(string strAlarmTime, string strDevIP, string strAlarmMsg);
        public delegate void UpdateListBoxCallbackException(string strAlarmTime, int lUserID, string strAlarmMsg);
      
        [DllImport("kernel32.dll")]
        public static extern bool Beep(int frequency, int duration);
        private static CMBDeviceManager cmbDeviceManager = CMBDeviceManager.Instance;
        static private ushort totalTemplateCapacity = 0;
        static private bool saveImageWhenEnroll = false;
        Dictionary<string, string> taskMap = new Dictionary<string, string>();

        string logicVersion = "1.24";
        string realVersion = "137";
        bool socketSatau = false;
        string ipAll = "";
        int readerTime = 0;
        bool turnOnFlag1 = true;
        bool turnOnFlag2 = true;
        string iconPattern = "";
        bool iconFlag = false;
        bool handoverFlag = false;
        string modelType = "";
        int epcLength = 10;
        long faceExpire = 0;
        int intervalTime = 10;
        string bussType = "";
        string deviceIp = "";
        string ftpPath = "";
        bool alarmFlag = false;
        bool yellowFlag = true;
        string gateIP = "";
        bool gateFlag = false;
        bool safeTy = true;
        string heartTime = "";
        public Form1()
        {
            InitializeComponent();
            //CheckForIllegalCrossThreadCalls = false;
           
            try
            {

               
                cmdFilePath = ConfigurationManager.AppSettings["FtpServerRoot"].ToString();
                comName = ConfigurationManager.AppSettings["ComName"].ToString();
                ServerIP = ConfigHelper.GetAppConfig("ServerIP");
                port = int.Parse(ConfigHelper.GetAppConfig("Port"));
                alarmFlag = bool.Parse(ConfigHelper.GetAppConfig("AlarmFlag"));
                safeTy = bool.Parse(ConfigHelper.GetAppConfig("SafeTy"));
                gateIP = ConfigHelper.GetAppConfig("GateIP");
                modelType = ConfigHelper.GetAppConfig("ModelType");
                gateTime = int.Parse(ConfigHelper.GetAppConfig("GateTime"));
                heartStatu = bool.Parse(ConfigHelper.GetAppConfig("HeartStatu"));
                logDays = int.Parse(ConfigHelper.GetAppConfig("LogDays"));
                PSAMReaderName = ConfigHelper.GetAppConfig("PSAMReaderName");
                ICReaderName = ConfigHelper.GetAppConfig("ICReaderName");
                ipAll = ConfigHelper.GetAppConfig("MjIP");
                readerTime = int.Parse(ConfigHelper.GetAppConfig("ReaderTime"));
                heartTime = ConfigHelper.GetAppConfig("HeartTime");

                openGateType = int.Parse(ConfigHelper.GetAppConfig("OpenGateType"));
                bussType = ConfigHelper.GetAppConfig("BussType");
                intervalTime = int.Parse(ConfigHelper.GetAppConfig("IntervalTime"));
                stackCode = ConfigHelper.GetAppConfig("StackCode");
                stackName = ConfigHelper.GetAppConfig("StackName");
                faceUseing = bool.Parse(ConfigHelper.GetAppConfig("FaceUseing"));
                //handoverFlag = bool.Parse(ConfigHelper.GetAppConfig("HandoverFlag"));
                //gateEncrypt = bool.Parse(ConfigHelper.GetAppConfig("GateEncrypt"));
                loginUser = bool.Parse(ConfigHelper.GetAppConfig("LoginUser"));
                ltScreen = new TXTHelper(cmdFilePath, "1.txt");
                ltScreenInfo = new TXTHelper(cmdFilePath, "2.txt");
                ltTaskInfo = new TXTHelper(cmdFilePath, "3.txt");
                iconFlag = bool.Parse(ConfigHelper.GetAppConfig("IconFlag"));

                iconPattern = ConfigHelper.GetAppConfig("IconPattern");
                
                //packFilter = ConfigHelper.GetAppConfig("PackFilter");
                debugButton = bool.Parse(ConfigHelper.GetAppConfig("DebugButton"));
                faceExpire = long.Parse(ConfigHelper.GetAppConfig("FaceExpire"));
                LogHelper.Debug("配置文件加载成功:ServerIP=" + ServerIP + "port" + port + " ComName=" + comName + "版本号" + logicVersion);
               
                LogHelper.Debug("配置文件加载成功:FtpServerRoot=" + cmdFilePath + " 日志保留时间" + logDays + "栅栏门中断时间" + gateTime);
                LogHelper.Debug("配置文件加载成功:IC读卡器名称=" + ICReaderName + " PSAM读卡器名称" + PSAMReaderName );
                LogHelper.Debug("配置文件加载成功:栅栏门刷卡开启人数=" + userGateCount + "用户免刷卡登陆" + loginUser + " 操作员和复核员" + auditorUser + ":" + operatorUser);
                LogHelper.Debug("配置文件加载成功:人脸设备是否启用" + faceUseing );
                LogHelper.Debug("real" + realVersion);
                if (!debugButton)
                {
                    this.button7.Visible = false;
                }
                //用户免刷卡登陆
                if (loginUser)
                {
                    flagLoginUser = true;
                }
                if (modelType.Equals("test"))
                {
                    epcLength = 9;
                }
                if (iconFlag)
                {
                    pictureBox1.Visible = true;
                    if (iconPattern.Equals("rtd"))
                    {
                        pictureBox1.Image = LoadPictureUtil.GetResourceImage("rtd");

                    }
                    else if (iconPattern.Equals("yyx"))
                    {
                        pictureBox1.Image = LoadPictureUtil.GetResourceImage("yyx");

                    }

                }
                else
                {
                    pictureBox1.Visible = false;
                }
               
                if (faceUseing == true)
                {
                    deviceIp = ConfigHelper.GetAppConfig("DeviceIp");
                    string devicePort = ConfigHelper.GetAppConfig("DevicePort");
                    string deviceUserName = ConfigHelper.GetAppConfig("DeviceUserName");
                    string devicePassword = ConfigHelper.GetAppConfig("DevicePassword");
                    LogHelper.Debug("deviceIp=" + deviceIp + "devicePort" + devicePort + "deviceUserName" + deviceUserName + "devicePassword" + devicePassword);
                    bool m_bInitSDK = CHCNetSDK.NET_DVR_Init();
                    if (m_bInitSDK == false)
                    {
                        MessageBox.Show("NET_DVR_Init error!");
                        return;
                    }
                    else
                    {
                        byte[] strIP = new byte[16 * 16];
                        uint dwValidNum = 0;
                        Boolean bEnableBind = false;



                        //保存SDK日志 To save the SDK log
                        CHCNetSDK.NET_DVR_SetLogToFile(3, "C:\\SdkLog\\", true);

                        //设置透传报警信息类型
                        CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG struLocalCfg = new CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG();
                        struLocalCfg.byAlarmJsonPictureSeparate = 1;//控制JSON透传报警数据和图片是否分离，0-不分离(COMM_VCA_ALARM返回)，1-分离（分离后走COMM_ISAPI_ALARM回调返回）

                        Int32 nSize = Marshal.SizeOf(struLocalCfg);
                        IntPtr ptrLocalCfg = Marshal.AllocHGlobal(nSize);
                        Marshal.StructureToPtr(struLocalCfg, ptrLocalCfg, false);

                        if (!CHCNetSDK.NET_DVR_SetSDKLocalCfg(17, ptrLocalCfg))  //NET_DVR_LOCAL_CFG_TYPE_GENERAL
                        {
                            iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                            strErr = "NET_DVR_SetSDKLocalCfg failed, error code= " + iLastErr;
                            MessageBox.Show(strErr);
                        }
                        Marshal.FreeHGlobal(ptrLocalCfg);

                        for (int i = 0; i < 200; i++)
                        {
                            m_lAlarmHandle[i] = -1;
                        }

                        //设置异常消息回调函数
                        if (m_fExceptionCB == null)
                        {
                            m_fExceptionCB = new CHCNetSDK.EXCEPYIONCALLBACK(cbExceptionCB);
                        }
                        CHCNetSDK.NET_DVR_SetExceptionCallBack_V30(0, IntPtr.Zero, m_fExceptionCB, IntPtr.Zero);


                        //设置报警回调函数
                        if (m_falarmData_V31 == null)
                        {
                            m_falarmData_V31 = new CHCNetSDK.MSGCallBack_V31(MsgCallback_V31);
                        }
                        CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(m_falarmData_V31, IntPtr.Zero);
                    }
                    CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();
                    //设备布防
                    CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
                    struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
                    struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
                    struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型
                    struAlarmParam.byDeployType = 1; //0客户端布防，1实时布防
                    struAlarmParam.byFaceAlarmDetection = 1;//1-人脸侦测
                    string[] deviceIpArr = deviceIp.Split(':');
                    foreach (string deviceIps in deviceIpArr)
                    {
                        if (deviceIps.Length > 5)
                        {
                            byte[] byIP = System.Text.Encoding.Default.GetBytes(deviceIps);
                            struLogInfo.sDeviceAddress = new byte[129];
                            byIP.CopyTo(struLogInfo.sDeviceAddress, 0);
                            //设备用户名
                            byte[] byUserName = System.Text.Encoding.Default.GetBytes(deviceUserName);
                            struLogInfo.sUserName = new byte[64];
                            byUserName.CopyTo(struLogInfo.sUserName, 0);

                            //设备密码
                            byte[] byPassword = System.Text.Encoding.Default.GetBytes(devicePassword);
                            struLogInfo.sPassword = new byte[64];
                            byPassword.CopyTo(struLogInfo.sPassword, 0);

                            struLogInfo.wPort = ushort.Parse(devicePort);//设备服务端口号

                            struLogInfo.cbLoginResult = LoginCallBack;
                            struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是 

                            if ((struLogInfo.bUseAsynLogin == true) && (LoginCallBack == null))
                            {
                                LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(cbLoginCallBack);//注册回调函数                    
                            }
                            struLogInfo.byLoginMode = 0; //0-Private, 1-ISAPI, 2-自适应
                            struLogInfo.byHttps = 0; //0-不适用tls，1-使用tls 2-自适应
                            CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

                            //登录设备 Login the device
                            m_lUserID = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
                            if (m_lUserID < 0)
                            {
                                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                                strErr = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号 Failed to login and output the error code
                                LogHelper.Debug(strErr);
                            }
                            else
                            {
                                //登录成功
                                iDeviceNumber++;
                                string str1 = "" + m_lUserID;
                                LogHelper.Debug("str1" + str1);



                                m_lAlarmHandle[m_lUserID] = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(m_lUserID, ref struAlarmParam);
                                if (m_lAlarmHandle[m_lUserID] < 0)
                                {
                                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                                    strErr = "布防失败，错误号：" + iLastErr; //布防失败，输出错误号
                                    LogHelper.Debug("布防失败，错误号：" + iLastErr);
                                    ltScreenInfo.WriteMessage("人脸识别设备布防失败");
                                }
                                else
                                {
                                    ltScreenInfo.WriteMessage("人脸识别设备布防成功");
                                    LogHelper.Debug("布防成功");
                                }
                            }
                        }
                    }



                }
            }
            catch (Exception e)
            {
                LogHelper.Debug("配置文件加载失败!" + e);
                this.Close();
            }
            try
            {
                ClearCMDFile();
                TXTHelper.deleteTxt(logDays);
                LogHelper.Debug("清除任务文件!");
                //加载蜂鸣声音
                sound = new SoundPlayer(AppDomain.CurrentDomain.BaseDirectory + "9779.wav");
                //ftp = new FtpHelper("127.0.0.1", "kcrx", "kcrx8888");
                //门架
                socketClientMJ = new socketClient(IPAddress.Parse(ServerIP), port, "2");


               

            }
            catch (Exception e)
            {
                LogHelper.Debug("删除日志及连接ftp失败!" + e);
                this.Close();
            }




        }
        public class LoadPictureUtil
        {
            public static Bitmap GetResourceBitmap(string imageName)
            {
                object obj = ControllerClient.Properties.Resources.ResourceManager.GetObject(imageName, ControllerClient.Properties.Resources.Culture);
                return (Bitmap)obj;
            }
            public static Image GetResourceImage(string imageName)
            {
                object obj = ControllerClient.Properties.Resources.ResourceManager.GetObject(imageName, ControllerClient.Properties.Resources.Culture);
                return (Image)obj;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                LogHelper.InitLogConfig("log4netConfig.xml");
                LogHelper.Debug("程序启动成功!");
               
                //    //启动文件检查
                if (!Directory.Exists(cmdFilePath))
                {
                    try
                    {
                        Directory.CreateDirectory(cmdFilePath);
                       
                        LogHelper.Debug("命令文件目录不存在，新建目录:" + cmdFilePath);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Debug("命令文件目录不存在，新建目录:失败", ex);
                    }
                }

               

                FileServer.FileChangEvent += new FileServer.FileChangeEventHandler(this.FileServer_FileChangEvent);
                FileServer.StartListener(cmdFilePath);

                
                readerIC = new PCSCReader(ICReaderName);
                //监听IC卡插入插出事件
                readerIC.startMonitor();
                PCSCReader.CardInsertEvent += PCSCReader_ICCardInsertEvent;
                PCSCReader.CardRemoveEvent += PCSCReader_ICCardRemoveEvent;
                

                readerPCSC = new PCSCReader(PSAMReaderName);
                readerPCSC.startMonitor();
                bool glag = readerPCSC.upPower();
              

                if (glag == false)
                {


                    ltScreenInfo.WriteMessage("程序启动失败!检测PSAM失败，请重启电脑");
                    //ShowInfo(informTb, "程序启动失败!检测PSAM失败，请重启电脑");

                }
                else
                {
                    LogHelper.Debug("上电状态" + glag);
                    controlId = readerPCSC.sendAPDU("8010010015");
                    controlId = controlId.Substring(0, 8);
                    ltScreenInfo.WriteMessage("程序启动成功，但未接入通讯组件!版本号"+ logicVersion);
                    readerPCSC.DownPower();
                    //ShowInfo(informTb, "程序启动成功，但未接入通讯组件!版本号" + logicVersion);
                }
                

                //if (!gateComFlag(yellowOn))
                //{
                //    ltScreenInfo.WriteMessage("栅栏门连接中断");
                //    sound.Play();
                //}

                //comCom(greenOff);
                //comCom(redOff);
                
               
               

            }
            catch (Exception ex)
            {
                LogHelper.Debug("load加载报错" + ex);
            }
            try
            {


                socketClient.HardwareInitializeEvent += new socketClient.HardwareInitializeHandler(this.HardwareInitialize);
                socketClient.APDUHandlerEvent += new socketClient.APDUHandler(this.DataExchange);
                socketClient.DownCommondEvent += new socketClient.DownCommondHandler(this.DownCommond);
                socketClient.CheckEnvironmentEvent += new socketClient.CheckEnvironmentHandler(this.CheckEnvironment);
                socketClient.JoinUpEvent += new socketClient.JoinUpHandler(this.JoinUp);
                socketClient.ErrorFeedbackEvent += new socketClient.ErrorFeedbackHandler(this.ErrorFeedback);
                socketClient.PowerManagerEvent += new socketClient.PowerManagerHandler(this.PowerManager);
                socketClient.ConfirmEvent += new socketClient.ConfirmHandler(this.DataConfirm);
                socketClient.ExecuteEvent += new socketClient.ExecuteHandler(this.DataExecute);
                socketClient.UserDataSyncEvent += new socketClient.UserDataSyncHandler(this.UserDataSync);
                socketClient.AuthorizedAccessEvent += new socketClient.AuthorizedAccessHandler(this.AuthorizedAccess);
               
                socketSatau=socketClientMJ.conn();
                
            }
            catch (Exception ex)
            {
                LogHelper.Debug("事件委托出错" + ex);
            }

        }
        public  void conn()
        {
           
            try
            {

                using (FtpServer server = new FtpServer())
                {
                    Console.WriteLine("测试帐号:anonymous(匿名登陆，具有读权限), ftp(密码:ftp,具有读写权限)");

                    /*
                     * 服务器的最大连接数
                     */
                    server.Capacity = 1000;
                    server.Port = 2121;

                    /*
                     * 连接超时时间
                     */
                    server.HeartBeatPeriod = 120000;  //120秒

                    /*
                     * 创建一个使用FTP的用户，
                     */
                    FtpUser user = new FtpUser("kcrx");
                    user.Password = "kcrx8888";
                    user.AllowWrite = true;
                    user.HomeDir = ftpPath;

                    /*
                     * 限制该帐号的用户的连接服务器的最大连接数
                     * 也就是限制该使用该帐号的FTP同时连接服务器的数量。
                     */
                    user.MaxConnectionCount = 3;

                    /*
                     * 限制用户的最大上传文件为20M，超过这个值上传文件会失败。
                     * 默认不限制该值，可以传输大文件。
                     */
                    user.MaxUploadFileLength = 1024 * 1024 * 20;
                    server.AddUser(user);

                    //把当前目录作为匿名用户的目录，测试目的(必须指定)
                    server.AnonymousUser.HomeDir = Environment.CurrentDirectory;

                    server.Start();
                    while (true) { Thread.Sleep(1000); }
                    //Console.WriteLine("Press enter to exit...");

                    //server.Stop();
                }
            }
            catch (System.Exception e)
            {
                NetDebuger.PrintErrorMessage("FATAL ERROR:" + e.Message);
            }

        }
        public void FileServer_FileChangEvent(String cmdfilename)
        {
            try
            {
                LogHelper.Debug("发现任务文件:" + cmdfilename, this.GetType());
                if (cmdfilename.EndsWith(".txt"))//如果是命令文件
                {
                    

                    if (cmdfilename.EndsWith("1.txt"))//这是进度数据文件
                    {
                        fileChangeEventHandler = new mFileChangeEventHandler(this.scheduleShow);
                        this.BeginInvoke(fileChangeEventHandler, cmdfilename);
                    }
                    if (cmdfilename.EndsWith("2.txt"))//这是信息提示文件
                    {
                        fileChangeEventHandler = new mFileChangeEventHandler(this.informShow);
                        this.BeginInvoke(fileChangeEventHandler, cmdfilename);
                    }
                    if (cmdfilename.EndsWith("3.txt"))//这是任务显示命令
                    {
                        fileChangeEventHandler = new mFileChangeEventHandler(this.taskShow);
                        this.BeginInvoke(fileChangeEventHandler, cmdfilename);
                    }
                    
                    //if (cmdfilename.EndsWith("5.txt"))//这是面向识别数据
                    //{
                    //    fileChangeEventHandler = new mFileChangeEventHandler(this.ifaceShow);
                    //    this.BeginInvoke(fileChangeEventHandler, cmdfilename);
                    //}
                }
                
            }
            catch (Exception e)
            {
                LogHelper.Debug("file" + e);
            }


        }
        #region  这是进度数据文件处理
        public void scheduleShow(String cmdfilename)
        {

            LogHelper.Debug("start***************************************************");
            try
            {
                Schedule nowSchedule = ScheduleTools.getSchedule(cmdfilename);
                if (nowSchedule != null)//空文件
                {


                    this.CommadLb.Text = nowSchedule.Cmdnum.ToString();
                    this.isScanLb.Text = nowSchedule.IsScannum.ToString();
                    this.notScanLB.Text = nowSchedule.NotScannum.ToString();
                    this.scanEpc.Text = nowSchedule.ScanEpc.ToString();
                    this.totalEpc.Text = nowSchedule.TotalEpc.ToString();
                    this.surplusEpc.Text = nowSchedule.SurplusEpc.ToString();
                    string[] epcs = nowSchedule.EpcList;
                    if (epcs == null)
                    {
                        LogHelper.Debug("不存在明细数据,无需更新列表");
                        LogHelper.Debug("任务处理完成:" + cmdfilename, this.GetType());
                        this.dataGridView1.Rows.Clear();
                        File.Delete(cmdfilename);
                        return;
                    }
                    else
                    {
                        for (int i = 0; i < epcs.Length; i++)
                        {
                            string[] arrays = epcs[i].Split(':');
                            string tag = arrays[0];
                            string voucherName = arrays[1];
                            string paperTypeName = "";
                            if (arrays.Length > 2) 
                            {
                                paperTypeName = arrays[2];
                            }
                            //TagEpcData ted = EpcReader.readEpc(StringAndBytesHelper.strToToHexByte(epcs[i]));
                            //string mess = ted.Lockstuts == false ? "开锁" : "关锁";


                            string messAll = "正常:正常" ;

                           
                            if (this.dataGridView1.Rows.Count == 1)//如果只有一行
                            {

                                this.dataGridView1.Rows.Add(tag, messAll, voucherName, paperTypeName);
                            }
                            else
                            {
                                if (chekRepeat(tag))
                                {
                                    this.dataGridView1.Rows.Add(tag, messAll, voucherName, paperTypeName);
                                }
                            }
                            
                            this.dataGridView1.Rows[this.dataGridView1.RowCount - 2].DefaultCellStyle.BackColor = Color.GreenYellow;
                            


                            this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.RowCount - 2;
                        }

                        LogHelper.Debug("任务处理完成:" + cmdfilename, this.GetType());
                        File.Delete(cmdfilename);
                    }
                    //scheduleTimer.Start();

                }
                LogHelper.Debug("end*****************************************************");
            }
            catch (Exception ex)
            {
                LogHelper.Debug("屏幕显示" + ex);
                LogHelper.Debug("任务处理失败:" + cmdfilename, this.GetType());
            }


        }
        private bool chekRepeat(string sackNo)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
            {
                if (this.dataGridView1.Rows[i].Cells[0].Value.Equals(sackNo))
                {
                    return false;
                }
            }
            return true;
        }
        //自动编号
        private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                //自动编号，与数据无关
                Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                   e.RowBounds.Location.Y,
                   dataGridView1.RowHeadersWidth - 4,
                   e.RowBounds.Height);
                TextRenderer.DrawText(e.Graphics,
                      (e.RowIndex + 1).ToString(),
                       dataGridView1.RowHeadersDefaultCellStyle.Font,
                       rectangle,
                       dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                       TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }
            catch (Exception ex)
            {
                LogHelper.Debug("ex" + ex);
            }
        }

        int stime = 0;
        private void scheduleTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                //System.Drawing.SystemColors.Control
                if (this.tableLayoutPanel2.BackColor != Color.GreenYellow)
                {
                    this.tableLayoutPanel2.BackColor = Color.GreenYellow;
                }
                else
                {
                    this.tableLayoutPanel2.BackColor = System.Drawing.SystemColors.Control;
                }
                stime++;
                // Console.Out.WriteLine("闪烁第" + stime+"次");
                if (stime > 11)
                {
                    scheduleTimer.Stop();
                    stime = 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug("scheduleTimer_Tick" + ex);
            }

        }
        public void taskShow(string cmdfilename)
        {
            try
            {
                TxtReader tr = new TxtReader(cmdfilename);
                this.informLb.Text = "";//清空原有提示
                string[] cmdstrs = tr.readUTF8();
                if (cmdstrs != null)
                {
                    foreach (string s in cmdstrs)
                    {
                        LogHelper.Debug("收到信息提示信息:" + s);


                        if (s.Split(':').Length > 0)
                        {
                            mess = s;
                            this.informLb.Text += s + "\r\n";

                        }

                    }
                    File.Delete(cmdfilename);
                }
                  
            }
            catch (Exception e)
            {
                LogHelper.Debug("收到信息提示信息错误", e);
            }

        }
        public void setShow(string cmdfilename)
        {
            try
            {
                TxtReader tr = new TxtReader(cmdfilename);
                string[] cmdstrs = tr.readUTF8();
                if (cmdstrs != null)
                {
                    foreach (string s in cmdstrs)
                    {
                        LogHelper.Debug("收到信息提示信息:" + s);
                       
                    }
                    //File.Delete(cmdfilename);
                }

            }
            catch (Exception e)
            {
                LogHelper.Debug("收到信息提示信息错误", e);
            }

        }
        #endregion
        #region  这是信息提示文件处理infoLines
        int infoLines = 0;
        string mess = "";
        public void informShow(string cmdfilename)
        {
            LogHelper.Debug("start***************************************************");
            Thread.Sleep(500);
            try
            {
                TxtReader tr = new TxtReader(cmdfilename);
                string[] cmdstrs = tr.readUTF8();

                
                if (cmdstrs != null)
                {
                    this.informTb.Text = "";//清空原有提示
                    foreach (string s in cmdstrs)
                    {
                        LogHelper.Debug("收到信息提示信息:" + s);


                        if (s.Split(':').Length > 0)
                        {
                            mess = s;
                            this.informTb.Text += s + "\r\n";

                        }
                        else
                        {
                            this.informTb.Text += s + "\r\n";
                        }


                    }
                    infoLines = cmdstrs.Length;
                    informTimer.Start();
                    LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
                    File.Delete(cmdfilename);
                }
               
            }
            catch (Exception e)
            {
                LogHelper.Debug("收到信息提示信息错误", e);

                // LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
            }

            LogHelper.Debug("end*****************************************************");
        }
        int informStime = 0;

        private void informTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (this.informTb.BackColor != Color.Red)
                {
                    this.informTb.BackColor = Color.Red;
                }
                else
                {
                    this.informTb.BackColor = Color.Blue;
                }
                informStime++;
                //this.informTb.Focus();//获取焦点
                //this.informTb.Select(selectLine, 0);//光标定位到文本最后
                //this.informTb.ScrollToCaret();//滚动到光标处

                //    selectLine++;


                if (informStime > 21)
                {
                    informTimer.Stop();
                    informStime = 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug("informTimer_Tick" + ex);
            }

        }
        #endregion
        #region 面向识别身份信息处理
        //public void ifaceShow(string cmdfilename)
        //{
        //    LogHelper.Debug("start***************************************************");
        //    try
        //    {
        //        LogHelper.Debug("收到面向识别身份信息，开始解析");
        //        TxtReader tr = new TxtReader(cmdfilename);
        //        string[] cmdstrs = tr.readUTF8();
        //        JObject JObject = JObject.Parse(cmdstrs[0]);
        //        string faceImageJson = JObject["regImage"].ToString();
        //        byte[] arr2 = Convert.FromBase64String(faceImageJson);

        //        using (MemoryStream ms2 = new MemoryStream(arr2))
        //        {
        //            System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
        //            this.ifacePb.Image = bmp2;
        //        }
        //        LogHelper.Debug("收到面向识别身份信息，解析完成");
        //        Thread.Sleep(1000);

        //        LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
        //    }
        //    catch (Exception e)
        //    {
        //        LogHelper.Debug("收到面向识别身份信息处理失败" + e);
        //    }
        //    LogHelper.Debug("end*****************************************************");
        //}
        #endregion
        #region 串口控制命令处理
        private void comCom(string cmdfilename)
        {
            LogHelper.Debug("start***************************************************");
            try
            {
                //TxtReader tr = new TxtReader(cmdfilename);
                //string[] cmdstrs = tr.readUTF8();
                string comStr = cmdfilename;
                this.serialPort1.PortName = comName;
                this.serialPort1.Open();
                byte[] ComBytes = StringAndBytesHelper.strToToHexByte(comStr);
                LogHelper.Debug("打开串口" + comName + "成功");
                this.serialPort1.Write(ComBytes, 0, ComBytes.Length);
                LogHelper.Debug("发送控制命令" + comStr + "成功");
                serialPort1.ReadTimeout = 2000;
                //Thread.Sleep(50);
                //int length = serialPort1.BytesToRead;
                //if (length < 8)
                //{
                //    ltScreenInfo.WriteMessage("栅栏门连接中断");
                //    sound.Play();
                //}
                this.serialPort1.Close();
                LogHelper.Debug("关闭串口" + comName + "成功");


                LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
                File.Delete(cmdfilename);
                LogHelper.Debug("删除串口命令文件完成:" + cmdfilename, this.GetType());
            }
            catch (Exception e)
            {
                ltScreenInfo.WriteMessage("栅栏门连接中断");
                sound.Play();
                LogHelper.Debug("发送串口控制命令失败", e);
            }
            LogHelper.Debug("end*****************************************************");
        }
        private void comComGate(string cmdfilename)
        {
            LogHelper.Debug("start***************************************************");
            try
            {
                //TxtReader tr = new TxtReader(cmdfilename);
                //string[] cmdstrs = tr.readUTF8();
                string comStr = cmdfilename;
                this.serialPort1.PortName = comName;
                this.serialPort1.Open();
                byte[] ComBytes = StringAndBytesHelper.strToToHexByte(comStr);
                LogHelper.Debug("打开串口" + comName + "成功");
                this.serialPort1.Write(ComBytes, 0, ComBytes.Length);
                LogHelper.Debug("发送控制命令" + comStr + "成功");
                serialPort1.ReadTimeout = 2000;
                //读取返回数据

                Thread.Sleep(50); //50毫秒内数据接收完毕，可根据实际情况调整
                byte[] recData = new byte[serialPort1.BytesToRead];
                serialPort1.Read(recData, 0, recData.Length);

                string gateHex = HexUtils.byteToHexStr(recData);
                LogHelper.Debug("回复结果gateHex" + gateHex);
                  
                if (!gateHex.Equals(comStr))
                {
                    ltScreenInfo.WriteMessage("栅栏门连接中断");
                    sound.Play();
                }
                this.serialPort1.Close();
                LogHelper.Debug("关闭串口" + comName + "成功");


                LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
                File.Delete(cmdfilename);
                LogHelper.Debug("删除串口命令文件完成:" + cmdfilename, this.GetType());
            }
            catch (Exception e)
            {
                ltScreenInfo.WriteMessage("栅栏门连接中断");
                sound.Play();
                LogHelper.Debug("发送串口控制命令失败", e);
            }
            LogHelper.Debug("end*****************************************************");
        }
        public bool gateComFlag(string cmdfilename)
        {
            bool flag = true;
            try
            {
                string comStr = cmdfilename;
                this.serialPort1.PortName = comName;
                this.serialPort1.Open();
                byte[] ComBytes = StringAndBytesHelper.strToToHexByte(comStr);
                LogHelper.Debug("打开串口" + comName + "成功");
                this.serialPort1.Write(ComBytes, 0, ComBytes.Length);
                LogHelper.Debug("发送控制命令" + comStr + "成功");
                serialPort1.ReadTimeout = 2000;
                Thread.Sleep(50);
                int length = serialPort1.BytesToRead;
                Console.WriteLine("===length" + length);
                if (length < 8)
                {
                    flag = false;
                }
                byte[] recData = new byte[serialPort1.BytesToRead];
                serialPort1.Read(recData, 0, recData.Length);

                string gateHex = HexUtils.byteToHexStr(recData);

                LogHelper.Debug("回复结果gateHex" + gateHex);
                if (!gateHex.Equals(comStr))
                {
                    flag = false;
                }
                this.serialPort1.Close();
                LogHelper.Debug("关闭串口" + comName + "成功");


                LogHelper.Debug("任务处理完成" + cmdfilename, this.GetType());
                File.Delete(cmdfilename);
                LogHelper.Debug("删除串口命令文件完成:" + cmdfilename, this.GetType());
            }
            catch (Exception e)
            {
                flag = false;
                LogHelper.Debug("发送串口控制命令失败", e);
            }

            return flag; 
        }
        #endregion
      
        private void label1_DoubleClick(object sender, EventArgs e)
        {
            Form2 fff = new Form2(iconPattern);
            fff.ShowDialog();
            if (fff.DialogResult == DialogResult.OK)
            {
                Application.Exit();
            }
        }
        private void ClearCMDFile()
        {

            try
            {
                String[] cmdfiles = Directory.GetFiles(cmdFilePath);
                if (cmdfiles.Length > 0)
                {
                    for (int i = 0; i < cmdfiles.Length; i++)
                    {
                        // Debug.WriteLine(cmdfiles[i]);
                        if (cmdfiles[i].EndsWith(".txt"))
                        {
                            File.Delete(cmdfiles[i]);
                        }
                    }
                }

            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.StackTrace);
            }
        }


        //开栅栏门
        private void AuthorizedAccess(byte[] data)
        {
            try
            {

                if (HexUtils.byteToHexStr(data).Equals("00000000"))
                {
                    LogHelper.Debug("开启栅栏门");

                    ltScreenInfo.WriteMessage("验证通过，开启栅栏门");
                    string[] ipArr = ipAll.Split(':');
                    for (int i = 0; i < ipArr.Length; i++)
                    {
                        string ip = ipArr[i];
                        if (ip.Length > 5 && !ip.Equals("127.0.0.1"))
                        {

                            List<String> list = readerMJ.mjEpcData(ip);
                            LogHelper.Debug("门架缓存" + list.Count);
                            Thread.Sleep(1000);
                            if (i == 0)
                            {
                                turnOnFlag1 = readerMJ.mjTurnOn(ip);
                                LogHelper.Debug("门架" + ip + "启动状态" + turnOnFlag1);
                            }
                            else if (i == 1)
                            {
                                turnOnFlag2 = readerMJ.mjTurnOn(ip);
                                LogHelper.Debug("门架" + ip + "启动状态" + turnOnFlag2);
                            }
                        }
                    }
                    flagUser = true;
                    if ( openGateType == 3)
                    {

                        myCol.Clear();
                        if (cardHash1.Count == userGateCount)
                        {
                            comComGate(gateOn);
                            Thread.Sleep(gateTime);
                            comCom(gateOff);
                            cardHash1.Clear();
                        }
                        if (cardHash2.Count == userGateCount)
                        {
                            comComGate(gateOn1);
                            Thread.Sleep(gateTime);
                            comCom(gateOff1);
                            cardHash2.Clear();
                        }
                        if (cardHash3.Count == userGateCount)
                        {
                            comComGate(gateOn2);
                            Thread.Sleep(gateTime);
                            comCom(gateOff2);
                            cardHash3.Clear();
                        }

                    }
                    else if (openGateType == 2)
                    {
                        comComGate(gateOn);
                        Thread.Sleep(gateTime);
                        comCom(gateOff);
                    }
                    else if (openGateType == 1)
                    {
                        flagFace = true;
                    }
                    
                   
                   
                  
                   
                }
                else
                {
                    string error = Encoding.UTF8.GetString(data);
                    LogHelper.Debug("授权开启栅栏门失败" + error);
                    ltScreenInfo.WriteMessage("授权开启栅栏门失败" + error);
                }
            }
            catch (Exception e)
            {
                LogHelper.Debug("授权开启栅栏门失败" + e);
            }

        }
        private static void ProgressCB(object user, int percent)
        {
            CMBDeviceManager mng = (CMBDeviceManager)user;
            ClearCurrentConsoleLine();
            Console.Write("Progress " + percent + "% percent on " + mng.ToString());
        }
        public static void ClearCurrentConsoleLine()
        {
            int currentLineCursor = Console.CursorTop;
            Console.SetCursorPosition(0, Console.CursorTop);
            for (int i = 0; i < Console.WindowWidth; i++)
                Console.Write(" ");
            Console.SetCursorPosition(0, currentLineCursor);
        }
        private static void SaveAsBitmap(string fileName, int width, int height, byte[] imageData)
        {
            ByteToGrayBitmap(imageData, width, height).Save(Path.ChangeExtension(fileName, ".bmp"));
        }
        public static Bitmap ByteToGrayBitmap(byte[] rawBytes, int width, int height)
        {
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height),
                 ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

            int offset = bmpData.Stride - bmpData.Width;
            IntPtr ptr = bmpData.Scan0;
            int scanBytes = bmpData.Stride * bmpData.Height;
            byte[] grayValues = new byte[scanBytes];

            int posSrc = 0, posScan = 0;
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    grayValues[posScan++] = rawBytes[posSrc++];
                }
                posScan += offset;
            }

            Marshal.Copy(grayValues, 0, ptr, scanBytes);
            bitmap.UnlockBits(bmpData);

            ColorPalette palette;
            using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                palette = bmp.Palette;
            }
            for (int i = 0; i < 256; i++)
            {
                palette.Entries[i] = Color.FromArgb(i, i, i);
            }
            bitmap.Palette = palette;

            return bitmap;
        }
       
        public static void ShowInfo(System.Windows.Forms.TextBox txtInfo, string Info)
        {
            txtInfo.Text = "";
            txtInfo.AppendText(Info);
            txtInfo.AppendText(Environment.NewLine);
            txtInfo.ScrollToCaret();
           

        }
        private void ErrorFeedback(string data)
        {
            try
            {
                string logicType = data.Split(':')[2];
                string payloads = data.Split(':')[1];
                sequence = data.Split(':')[0];
                if (payloads.Length > 0)
                {
                    string level = payloads.Substring(0, 2);
                    string content = "";
                    switch (level)
                    {
                        case "FF":
                            content = "灾难信息";
                            break;
                        case "00":
                            content = "一般";
                            break;
                        case "01":
                            content = "警告";
                            break;
                        case "02":
                            content = "错误";
                            break;
                    }

                    int messLen = Convert.ToInt32(payloads.Substring(2, 8), 16) * 2;

                    string mess = Encoding.UTF8.GetString(HexUtils.strToHexByte(payloads.Substring(10, messLen)));
                    LogHelper.Debug(content + ":" + mess);
                    if (mess.Equals("该设备已经下发过任务"))
                    {

                        string cmd = ltTaskCmd.ReadMessage();
                        //获取结果
                        string result = ltTaskData.ReadMessage();

                        if (result != null && !result.Contains("手持机数据上传失败,手持机任务未完成"))
                        {

                            //sequence = ltMJSequence.ReadMessage();

                            byte[] commond = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", result, operatorUser, auditorUser);
                            socketClientMJ.sendAsynchronous(commond);
                        }

                    }
                    if (level.Equals("FF"))
                    {
                        mess = mess + "请人工介入";
                        ltScreenInfo.WriteMessage("重大" + content + ":" + mess);
                        socketClientMJ.soekctClose();
                        //Thread.Sleep(3000);
                        //Application.Exit();
                    }
                    
                    if (mess.Equals("不应被展示"))
                    {
                        ltScreenInfo.WriteMessage("存在安全问题，请人工介入");
                        socketClientMJ.soekctClose();
                    }
                    else 
                    {
                        ltScreenInfo.WriteMessage(content + ":" + mess);
                        Thread.Sleep(1000);
                    }
                }
                else 
                {
                    ltScreenInfo.WriteMessage("存在安全问题，请人工介入");
                    socketClientMJ.soekctClose();
                }
                
                
                //ShowInfo(informTb, content + ":" + mess);
            }
            catch (Exception e)
            {
                LogHelper.Debug("==" + e);
            }

        }

        private void UserDataSync(string data)
        {
            try
            {
                //string logicType = data.Split(':')[2];
                userInfo = "";
                string payloads = data.Split(':')[1];
                sequence = data.Split(':')[0];
                string encryIndicate = data.Split(':')[3];
                byte[] commond = null;

                int metadataLen = Convert.ToInt32(payloads.Substring(0, 8), 16) * 2;
                string call = payloads.Substring(8, metadataLen);
                LogHelper.Debug("call" + Encoding.UTF8.GetString(HexUtils.strToHexByte(call)));
                string metamark = payloads.Substring(payloads.Length - 2);
                //string dataSouce = ltMetamark.ReadMessage();
                //if (!metamark.Equals(dataSouce))
                //{
                ltMetamark.WriteMessage(metamark);
                string mess = "";
                int i = 0;
                DataSync ds = JsonConvert.DeserializeObject<DataSync>(Encoding.UTF8.GetString(HexUtils.strToHexByte(call)));
                userGateCount = ds.RequiredUsers;
                LogHelper.Debug("出入库刷卡要求" + userGateCount);
                foreach (userInfo ui in ds.UserInfoList)
                {
                    i++;
                    string uid = ui.Uid;
                    string cid = ui.Cid;
                    string name = ui.Name;
                    string[] privileges = ui.Privileges;
                    string str = uid + ":" + cid + ":" + name + ":";
                    foreach (string pri in privileges)
                    {
                        str = str + pri + ":";
                    }
                    mess = mess + str + ";";

                    userList.Add(str);
                    if (loginUser)
                    {
                        if (i == 1)
                        {
                            auditorUser = uid;
                            operatorUser = uid;

                        }
                        else if (i == 2)
                        {
                            operatorUser = uid;
                        }
                    }
                    

                }
               
                    LogHelper.Debug("mess" + mess);
                    userInfo = mess;
                    ltUserInfo.WriteMessage(mess);
                

                commond = CommondHelper.DownCommond("", "2005", sequence, encryIndicate);
              
               socketClientMJ.send(commond);
                    
                flagPrompt = true;
                //开启待办标识
                toDealFlag = true;
            }
            catch (Exception e)
            {
                LogHelper.Debug("==" + e);
            }
        }
        private void PCSCReader_ICCardRemoveEvent(CardStatusEventArgs e)
        {
            try
            {


                LogHelper.Debug("收到卡拔出感应事件 ART=" + StringAndBytesHelper.ToHexString(e.Atr, e.Atr.Length));

                string atr = StringAndBytesHelper.ToHexString(e.Atr, e.Atr.Length);

            }
            catch (Exception ex)
            {
                LogHelper.Debug("卡拔出感应事件出错" + ex);
            }

        }

        private void PCSCReader_ICCardInsertEvent(CardStatusEventArgs e)
        {
            try
            {


                LogHelper.Debug("收到卡插入感应事件 ART=" + StringAndBytesHelper.ToHexString(e.Atr, e.Atr.Length));
                string atr = StringAndBytesHelper.ToHexString(e.Atr, e.Atr.Length);
                readerIC.upPower();
                string sw = readerIC.sendAPDU("802007000849434643434B4633");

                sw = readerIC.sendAPDU("80200600083132333435363738");

                sw = readerIC.sendAPDU("80200200084346434341433032");

                sw = readerIC.sendAPDU("80A4000002AA01");

                sw = readerIC.sendAPDU("80B200000A");

                string cardnum = sw.Substring(0, sw.Length - 4);
                string cmp = sw.Substring(sw.Length - 4, 4);
                byte[] cardByte = HexUtils.strToHexByte(cardnum);
                cardnum = Encoding.Default.GetString(cardByte);
                LogHelper.Debug("flagGate" + flagGate + "cardnum" + cardnum);
                LogHelper.Debug("userInfo" + userInfo);
                if (cmp.Equals("9000"))
                {
                    if (userInfo.Contains(cardnum))
                    {


                        foreach (string item in userList)
                        {
                            //开启栅栏门刷卡用户且 收到入库指令
                            if (item.Contains(cardnum) && item.Contains("isolate") && flagGate)
                            {
                                
                                cardAll = cardAll + cardnum + ",";
                                //userGateCheck++;
                                cardUserHash.Add(item.Split(':')[0]);
                                ltScreenInfo.WriteMessage("用户" + cardnum + "已刷卡通过");
                                LogHelper.Debug("已刷卡用户数" + cardUserHash.Count);
                                
                                

                            }
                            if (flagAlarm)
                            {
                                ltScreenInfo.WriteMessage("用户" + cardnum + "已刷卡解除警报");
                                flagAlarm = false;
                                sound.Stop();
                                comCom(redOff);
                                comCom(greenOn);
                            }
                            //用户登陆刷卡
                            if (!flagLoginUser && item.Contains(cardnum))
                            {
                                //userLoginCheck++;
                                cardLoginHash.Add(cardnum);
                                userLogin = userLogin + item.Split(':')[0] + ",";
                            }
                        }

                    }
                    else
                    {
                        ltScreenInfo.WriteMessage("该卡号" + cardnum + "无效");
                        // ftp.Upload(twoFile, "2.txt");

                    }

                }
                else
                {
                    LogHelper.Debug("读取IC卡ID失败：失败原因[" + sw + "]");
                }
                if (cardLoginHash.Count == 2)
                {
                    flagLoginUser = true;

                    auditorUser = userLogin.Split(',')[0];
                    operatorUser = userLogin.Split(',')[1];
                    cardLoginHash.Clear();
                    ltScreenInfo.WriteMessage("用户登陆成功");
                    //ftp.Upload(twoFile, "2.txt");
                    LogHelper.Debug("操作人" + auditorUser + "复核人" + operatorUser);
                }
                if (userGateCount == cardUserHash.Count && openGateType != 3)
                {
                    LogHelper.Debug("提交用户数据");
                    //flagGate = false;
                    foreach (string res in cardUserHash)
                    {
                        userGate = userGate + res + ",";
                    }
                    LogHelper.Debug("符合的用户" + userGate+"库间编号"+ stackCode);
                    byte[] commond = CommondHelper.UserEmpower(stackCode, "4003", "11", userGate, userGateCount, sequence);


                    socketClientMJ.send(commond);

                    cardUserHash.Clear();
                    userGate = "";
                }

            }
            catch (Exception ex)
            {
                LogHelper.Debug("卡插入感应事件出错" + ex);
            }
        }

        //当前版本号
        string version = "1.0.3";

        //逻辑硬件初始化1001
        private void HardwareInitialize(string data)
        {
            try
            {

                string versionGet = data.Split(':')[0];
                //string logicType = data.Split(':')[1];
                byte[] commond = null;
                //version = "1.0.6";
                string prefix = iconPattern;
                //if (!version.Equals(versionGet))
                //{
                //    prefix = "";
                //}
                //else 
                //{
                //    version = "1.2.4";
                //}

                commond = CommondHelper.HardwareInitialize(controlId, safeTy, heartTime, iconPattern, prefix, versionGet, heartStatu, "1001", "00", "2");
                socketClientMJ.send(commond);
               
               
               
               

            }
            catch (Exception e)
            {
                LogHelper.Debug("初始化出错" + e);
            }

        }
        //检查环境1004
        private void CheckEnvironment(string data)
        {
            try
            {


                sequence = data.Split(':')[0];
                string content = data.Split(':')[1];
                string encryIndicate = data.Split(':')[3];
                if (!content.Equals("00000000"))
                {
                    content = content.Substring(8);
                    string contentCH = Encoding.UTF8.GetString(HexUtils.strToHexByte(content));
                    LogHelper.Debug("contentCH" + contentCH);
                    ltScreenInfo.WriteMessage(contentCH + "请重启软件");
                    socketClientMJ.soekctClose();
                }
                else
                {
                    byte[] commond = CommondHelper.DownCommond("", "1004", sequence, encryIndicate);                    
                    socketClientMJ.send(commond);
                }
               
               
               
                

            }
            catch (Exception e)
            {
                LogHelper.Debug("检查环境出错" + e);
            }

        }
        [DllImport("kernel32.dll")]
        private static extern bool SetLocalTime(ref SYSTEMTIME time);

        [StructLayout(LayoutKind.Sequential)]
        private struct SYSTEMTIME
        {
            public short year;
            public short month;
            public short dayOfWeek;
            public short day;
            public short hour;
            public short minute;
            public short second;
            public short milliseconds;
        }
       
        public static bool SetDate(DateTime dt)
        {
            SYSTEMTIME st;

            st.year = (short)dt.Year;
            st.month = (short)dt.Month;
            st.dayOfWeek = (short)dt.DayOfWeek;
            st.day = (short)dt.Day;
            st.hour = (short)dt.Hour;
            st.minute = (short)dt.Minute;
            st.second = (short)dt.Second;
            st.milliseconds = (short)dt.Millisecond;
            bool rt = SetLocalTime(ref st);
            LogHelper.Debug("更改系统时间" + rt+"==="+ st.minute);

            return rt;
        }

        //接入1005
        private void JoinUp(string data)
        {
            try
            {


                sequence = data.Split(':')[0];
                string datetime = data.Split(':')[1];
                string encryIndicate = data.Split(':')[4];
                byte[] commond = CommondHelper.DownCommond("", "1005", sequence, encryIndicate);
                System.DateTime currentTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                DateTime time = currentTime.AddTicks(HexUtils.ToInt64(HexUtils.strToHexByte(datetime)) * 10000);
                //LogHelper.Debug("时间同步===" + HexUtils.ToInt64(HexUtils.strToHexByte(datetime)) * 10000);

                LogHelper.Debug("时间同步" + datetime+"===="+ time);
                SetDate(time);

                socketClientMJ.send(commond);
                ltScreenInfo.WriteMessage("门架接入成功");

                
                
                //加载门架
                readerMJ = new Reader();
                heartStart = true;
            }
            catch (Exception e)
            {
                LogHelper.Debug("接入出错" + e);
            }
        }
        //电源管理8001上电和下电
        bool commmitFlag = false;
        private void PowerManager(string data)
        {
            try
            {

                sequence = data.Split(':')[0];
                string payloads = data.Split(':')[1];
                string encryIndicate = data.Split(':')[2];
               // string logicType = data.Split(':')[4];
                string tag = payloads.Substring(0, 2);
                string str = payloads.Substring(2, 8);
                LogHelper.Debug("sequence" + sequence);
                LogHelper.Debug("tag上下电标识" + tag);
                string error = "";
                
                byte[] commond = null;
                if (tag.Equals("01"))
                {
                    LogHelper.Debug("上电");
                    if (!str.Equals("80000000"))
                    {
                        error = "power on is fail";
                    }
                    commond = CommondHelper.PowerManager(error, sequence, "8001", encryIndicate);
                    commmitFlag = false;
                }
                else if (tag.Equals("02"))
                {
                    if (!str.Equals("00000000"))
                    {
                        error = "power off is fail";
                    }
                    
                    LogHelper.Debug("下电");
                    commond = CommondHelper.PowerOff(error, sequence, "8001", encryIndicate);
                    commmitFlag = true;
                }
                else 
                {
                    error = "not recognition";
                    commond = CommondHelper.PowerOff(error, sequence, "8001", encryIndicate);
                    commmitFlag = false;
                }




                socketClientMJ.send(commond);
              
            }
            catch (Exception e)
            {
                LogHelper.Debug("8001电源管理出错" + e);
            }

        }
        //数据交换
        private void DataExchange(string data)
        {
            try
            {

                sequence = data.Split(':')[0];
                string mess = data.Split(':')[1];
                string encryIndicate = data.Split(':')[2];
                //string logicType = data.Split(':')[4];
                byte[] commond = CommondHelper.dataExchange("", dataControl,sequence, mess, "8002", encryIndicate);
                
                    socketClientMJ.send(commond);
                dataControl = "";


            }
            catch (Exception e)
            {
                LogHelper.Debug("数据交换出错" + e);
                ltScreenInfo.WriteMessage("数据交换出错,请重启程序");
            }
        }
        public static ArrayList removeDuplicate(ArrayList list)
        {
            for (int i = 0; i < list.Count - 1; i++)
            {
                for (int j = list.Count - 1; j > i; j--)
                {
                    if (list[i].Equals(list[j]))
                    {
                        list.RemoveAt(j);
                        if (i > 0) { i--; }
                    }
                        
                }
            }

            return list;
        }
        private void machineControl(string data)
        {
            LogHelper.Debug("2006收到" + Encoding.UTF8.GetString(HexUtils.strToHexByte(data.Substring(8))));
            int metadataLen = Convert.ToInt32(data.Substring(0, 8), 16) * 2;
            string call = data.Substring(8, metadataLen);
            LogHelper.Debug("call" + Encoding.UTF8.GetString(HexUtils.strToHexByte(call)));
            MachineControlCMD mc = JsonConvert.DeserializeObject<MachineControlCMD>(Encoding.UTF8.GetString(HexUtils.strToHexByte(call)));
            string control = mc.Control;
            string version = mc.Version;
            string verb = mc.Verb;
            stackCode = mc.StackCode;
            stackName = mc.StackName;
            LogHelper.Debug("栅栏门开关标识" + verb);
            ltScreenInfo.WriteMessage(stackName + "栅栏门需" + verb);

            MachineControlData mcd = new MachineControlData();
            response res = new response();
            res.Reply = "CTRL REPLY BARRTER";
            res.Sucess = "true";
            if (verb.Equals("open"))
            {

                LogHelper.Debug("栅栏门开启");
                flagMJ = true;
                flagUser = true;
                comCom(gateOn);
                Thread.Sleep(gateTime);
                comCom(gateOff);
            }
            else
            {
                LogHelper.Debug("栅栏门关闭");
                comCom(gateOn);
                Thread.Sleep(gateTime);
                comCom(gateOff); ;
            }
            var serializerSettings = new JsonSerializerSettings
            {
                // 设置为驼峰命名
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            //string str = "\"error\":\"\",\"respnose\":{\"reply\":\"CTRL REPLY BARRTER\",\"sucess\":\"true\"}";
            string json = JsonConvert.SerializeObject(res, Newtonsoft.Json.Formatting.None, serializerSettings);

            LogHelper.Debug("json" + json);
            byte[] commond = CommondHelper.MachineControlCommond("", json, "2006", sequence, "00");

            socketClientMJ.send(commond);

        }

        //下发

        string epcDataPlan = "";
        //StringBuilder epcDataPlan = new StringBuilder();
        long moneyPlan = 0;
        int jihua = 0;
        string messInfo = "";
        string messTask = "";
        bool isPass = false;
        long timeGet = 0;
        string dataControl = "";
        private void DownCommond(string data)
        {
            try
            {
                string[] ipArr = ipAll.Split(':');
                bool flag1 = readerMJ.mjTurnOff(ipArr[0]);
                if (!ipArr[1].Equals("127.0.0.1"))
                {
                    bool flag2 = readerMJ.mjTurnOff(ipArr[1]);
                    LogHelper.Debug("门架2关闭状态" + flag2);
                }
               
                LogHelper.Debug("门架1关闭状态" + flag1 );

                gateFlag = false;
                epcList.Clear();
                flagUser = false;
                flagFace = false;
                errorList.Clear();
                notTaskList.Clear();
                sequence = data.Split(':')[0];
                //string taskId = "0"+data.Split(':')[1].Substring(1,7);
                string taskId = data.Split(':')[1];
                string encryIndicate = data.Split(':')[4];
                string error = "";
                string ddd = HexUtils.HexStringToBinString(data.Split(':')[1]);
                LogHelper.Debug("联脱机标识" + ddd);

                byte[] commond = CommondHelper.DownCommond(error, "2002", sequence, encryIndicate);
                socketClientMJ.sendAsynchronous(commond);
                string dateTime = data.Split(':')[2];
               
                timeGet = HexUtils.ToInt64(HexUtils.strToHexByte(dateTime)) * 10000;
                System.DateTime currentTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

                DateTime time = currentTime.AddTicks(HexUtils.ToInt64(HexUtils.strToHexByte(dateTime)) * 10000);

                string dataTo = data.Split(':')[3];
                string dataToPDA = dataTo.Substring(8);
                dataToPDAFinal = Encoding.UTF8.GetString(HexUtils.strToHexByte(dataToPDA));

                LogHelper.Debug("2002任务id" + taskId);
               

                if (ddd.Substring(0, 1).Equals("1"))
                {
                    ltid.WriteMessage(taskId);
                    TXTHelper taskRead = new TXTHelper(taskId + "TaskCmd");
                    taskRead.WriteMessage(dataToPDAFinal);

                    //taskCmdMaker = new TXTHelper(taskId + "TaskCmd");
                    //taskCmdMaker.WriteMessage(dataToPDAFinal);

                }
               
                
                try
                {
                    taskMap.Add(taskId, dataToPDAFinal);
                }
                catch (Exception e)
                {
                    LogHelper.Debug("下发出错" + e);
                }

                ToDoTask todo = new ToDoTask();
                todo.TaskId = taskId+":不可执行"+ ":" + time;
                todo.TaskMsg = dataToPDAFinal;
                taskList.Add(todo);
                LogHelper.Debug("error==" + error);
                //JObject jo = JObject.Parse(dataToPDAFinal);
                //string code = jo["code"].ToString();
                // LogHelper.Debug("下发code为" + code);

                epcDataPlan = "";
                //epcDataPlan.Clear();

                dataControl = taskId + ":" + dateTime + ":" + dataTo + ":0:0" ;


            }
            catch (Exception e)
            {
                LogHelper.Debug("下发出错" + e);
            }
        }

        //确认
        private void DataConfirm(string data)
        {
            try
            {

                sequence = data.Split(':')[0];
                string payloadsStr = data.Split(':')[1];
                string encryIndicate = data.Split(':')[2];
                //string logicType = data.Split(':')[3];
                string id = payloadsStr.Substring(0, 8);
                string fragment = payloadsStr.Substring(8, 8);
                string complete = payloadsStr.Substring(16, 4);
                string completeBin = HexUtils.HexStringToBinString(complete);
                completeBin = completeBin.Replace(" ", "");
                LogHelper.Debug("completeBin" + completeBin);
                string deleteIf = completeBin.Substring(0, 1);
                string validateIf = completeBin.Substring(14, 1);
                string acceptIf = completeBin.Substring(15, 1);
                LogHelper.Debug("是否删除:" + deleteIf + "验证是否失败:" + validateIf + "是否被通讯组件接收:" + acceptIf);
              

                byte[] commond = CommondHelper.DownCommond("", "2004", sequence, encryIndicate);
               
                    socketClientMJ.sendAsynchronous(commond);

                    //string ipAll = ConfigHelper.GetAppConfig("MjIP");
                    //string[] ipArr = ipAll.Split(':');
                    //for (int i = 0; i < ipArr.Length; i++)
                    //{
                    //    bool flag = readerMJ.mjTurnOff(ipArr[i]);
                    //    LogHelper.Debug("门架关闭" + ipArr[i] + flag);
                    //}
                epcList.Clear();
                //
                errorList.Clear();
                notTaskList.Clear();
                if (deleteIf.Equals("1") && validateIf.Equals("0") && acceptIf.Equals("0"))
                {
                    flagGate = false;
                    foreach (var item in taskMap)
                    {
                        Console.WriteLine($"key={item.Key},value={item.Value}");
                        if (item.Key.Substring(1, 7).Equals(id.Substring(1, 7)))
                        {
                            id = item.Key;                            
                           


                        }

                    }
                    executeList.Remove(id);
                    taskMap.Remove(id);
                    //TXTHelper.deleteByTask("TaskCmd.txt");
                    TXTHelper.deleteByTask(id + "TaskCmd.txt");
                    LogHelper.Debug(id + "任务已删除");
                    if (id.Substring(1, 7).Equals(ltid.ReadMessage().Substring(1, 7)))
                    {
                        TXTHelper.deleteByTask("id.txt");
                    }
                    TXTHelper.deleteByTask(id + "data.txt");

                    LogHelper.Debug(id + "任务已删除");
                    ltScreenInfo.WriteMessage(id+"任务已删除");
                    ltScreen.WriteClear();
                    ltScreen.WriteLineNoTime("[03]任务总金额[03]0[03]元");
                    ltScreen.WriteLineNoTime("[01]已扫描金额[01]0[01]元");
                    ltScreen.WriteLineNoTime("[07]剩余金额[07]0[07]元");
                    ltScreen.WriteLineNoTime("[01]任务总袋数[01]0[01]袋数");
                    ltScreen.WriteLineNoTime("[01]已扫描袋数[01]0[01]袋数");
                    ltScreen.WriteLineNoTime("[01]剩余袋数[01]0[01]袋数");
                    LogHelper.Debug("当前无业务" );
                    ltTaskInfo.WriteMessage("当前无业务");
                    flagUser = false;
                    //ftp.Upload(oneFile, "1.txt");
                }
                else if (deleteIf.Equals("0") && validateIf.Equals("1") && acceptIf.Equals("0"))
                {
                    ltScreenInfo.WriteMessage("上传成功,但未被通讯接受");
                    yellowFlag = true;
                    comCom(yellowOn);
                    Thread.Sleep(500);
                    comCom(greenOff);
                    Thread.Sleep(500);
                    comCom(redOff);
                }
                else if (deleteIf.Equals("0") && validateIf.Equals("1") && acceptIf.Equals("1"))
                {
                    ltScreenInfo.WriteMessage("上传成功,但通讯组件验证异常");
                    yellowFlag = true;
                    comCom(yellowOn);
                    Thread.Sleep(500);
                    comCom(greenOff);
                    Thread.Sleep(500);
                    comCom(redOff);
                }
                else if (deleteIf.Equals("0") && validateIf.Equals("0") && acceptIf.Equals("0"))
                {
                    ltScreenInfo.WriteMessage("上传成功，已被通讯组件接收");
                    //flagUser = false;
                    yellowFlag = true;
                    comCom(yellowOn);
                    Thread.Sleep(500);
                    comCom(greenOff);
                    Thread.Sleep(500);
                    comCom(redOff);
                    gateFlag = true;
                    epcList.Clear();
                    bc.Code = 111;
                }

             


            }
            catch (Exception e)
            {
                LogHelper.Debug("确认出错" + e);
            }
        }
        //执行
        List<string> executeList = new List<string>();
        private void DataExecute(string data)
        {
            try
            {
                string taskId = data.Split(':')[1];

                executeList.Add(taskId);

                 yellowFlag = false;
                sequence = data.Split(':')[0];
                string encryIndicate = data.Split(':')[2];
                LogHelper.Debug("2003任务id" + taskId);
                string error = "";

                taskIdSend = taskId;
                if (taskMap.Count == 0)
                {
                    error = "任务已删除";
                }
                bool removeFalg = false;
                foreach (var item in taskMap)
                {
                    Console.WriteLine($"key={item.Key},value={item.Value}");
                    if (item.Key.Substring(1, 7).Equals(taskId.Substring(1, 7)))
                    {
                        error = "";
                        dataToPDAFinal = item.Value;
                        removeFalg = true;
                        Console.WriteLine("dataToPDAFinal===" + dataToPDAFinal);

                    }
                    
                }
                if (!removeFalg) { error = taskId + "任务已删除"; }
                string readId = ltid.ReadMessage();
                LogHelper.Debug("脱机存储id" + readId);
                if (readId.Length > 0)
                {
                    if (taskId.Substring(1, 7).Equals(readId.Substring(1, 7)))
                    {
                        error = "";
                        ltScreenInfo.WriteMessage("收到脱机任务" + taskId);
                        TXTHelper taskRead = new TXTHelper(readId + "TaskCmd");

                        string dataRead = taskRead.ReadMessage();

                        if (dataRead.Length > 0) { dataToPDAFinal = dataRead; }



                    }
                }
                
                byte[] commond = CommondHelper.DownCommond(error, "2003", sequence, encryIndicate);
                
                    socketClientMJ.sendAsynchronous(commond);

                //开启绿灯，关闭黄灯
                comCom(greenOn);
                
                comCom(yellowOff);

                string[] ipArr = ipAll.Split(':');
                for (int i = 0; i < ipArr.Length; i++)
                {
                    string ip = ipArr[i];
                    if (ip.Length > 5 && !ip.Equals("127.0.0.1"))
                    {

                        List<String> list = readerMJ.mjEpcData(ip);
                        LogHelper.Debug("门架缓存" + list.Count);
                        Thread.Sleep(1000);
                            turnOnFlag1 = readerMJ.mjTurnOn(ip);
                            LogHelper.Debug("门架" + ip + "启动状态" + turnOnFlag1);
                            if (!turnOnFlag1)
                            {
                                ltScreenInfo.WriteMessage("门架" + ip + "启动失败");
                            }
                        
                        
                    }
                }
                foreach (ToDoTask task in taskList)
                {
                    string idd = task.TaskId.Split(':')[0];
                    Console.WriteLine("id===" + idd + "===" + taskId);
                    if (idd.Substring(1, 7).Equals(taskId.Substring(1, 7)))
                    {
                        //可执行
                        task.TaskId = idd + ":可执行"+ task.TaskId.Split(':')[2];
                    }
                   
                }
                LogHelper.Debug("执行业务" + dataToPDAFinal);
                Thread.Sleep(1000);
                ltTaskCmd.WriteMessage(dataToPDAFinal);
                if (dataToPDAFinal.Length > 0)
                {
                    this.button5.Enabled = true;
                    error = "";
                    JObject jo = JObject.Parse(dataToPDAFinal);
                    string code = jo["code"].ToString();
                    LogHelper.Debug("下发code为" + code);
                    string messInfo = "";
                    string messTask = "";
                    epcDataPlan = "";
                    mustOutSack = false;

                    switch (code)
                    {
                        case ("131074"):
                            sackMap.Clear();
                            if (openGateType == 3)
                            {
                                messInfo = "出库业务，请刷脸开启栅栏门";
                            }
                            else
                            {
                                messInfo = "出库业务，请刷卡开启栅栏门";
                            }

                            messTask = "出库业务";

                            //stackCode = ((JArray)jo["stockPackInfoList"])[0]["sstackCode"].ToString();
                            osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                            foreach (outScanStockPackInfo ossp in osc.StockPackInfoList)
                            {
                                string sackNo = ossp.SackNo;
                                string voucher = ossp.VoucherTypeID;
                                string mustOutFlag = ossp.MustOutFlag;
                                epcDataPlan = epcDataPlan + sackNo + ":";
                                sackMap.Add(sackNo, voucher);
                                if (mustOutFlag.Equals("1"))
                                {
                                    mustOutSack = true;
                                    mustSackNo = mustSackNo + sackNo + ":";
                                }
                            }

                            break;
                        case ("131075"):
                            if (openGateType == 3)
                            {
                                messInfo = "入库业务，请刷脸开启栅栏门";
                            }
                            else
                            {
                                messInfo = "入库业务，请刷卡开启栅栏门";
                            }
                            messTask = "入库业务";
                            //stackCode = ((JArray)jo["stackInfoList"])[0]["sstackCode"].ToString();
                            esc = (EnterScanCMD)JsonConvert.DeserializeObject<EnterScanCMD>(dataToPDAFinal);
                            moneyPlan = 0;

                            jihua = esc.PaymentSackList.Length;
                            string valStr = "";
                            notScanList.Clear();
                            //遍历计划内的锁条号和金额
                            foreach (paymentSack ps in esc.PaymentSackList)
                            {
                                string sackNo = ps.SackNo;
                                string sackMoney = ps.SackMoney;
                                string val = ps.Val;
                                moneyPlan = moneyPlan + long.Parse(sackMoney.Split('.')[0]);
                                epcDataPlan = epcDataPlan + sackNo + ":";
                                valStr = valStr + val + ":";
                                notScanList.Add(sackNo);

                            }
                            


                            break;
                        case ("131078"):
                            messInfo = "日核对业务，请刷卡开启栅栏门";
                            messTask = "日核对业务";

                            break;
                        case ("131073"):
                            messInfo = "空包袋登记业务，如需进库请刷卡开启栅栏门";
                            messTask = "空包袋登记业务";
                            bool turnOnFlag = true;

                            
                            flagUser = true;
                            break;
                        case ("131079"):
                            messInfo = "非业务进出库，请刷卡开启栅栏门";
                            messTask = "非业务进出库";
                            //stackCode = ((JArray)jo["stacks"])[0]["id"].ToString();
                            LogHelper.Debug("库间名称" + stackCode + "意图" + ((JArray)jo["stacks"])[0]["intention"].ToString());
                            messInfo = messInfo + ((JArray)jo["stacks"])[0]["intention"].ToString();
                            NoBusinessCMD nbc = (NoBusinessCMD)JsonConvert.DeserializeObject<NoBusinessCMD>(dataToPDAFinal);
                            string spbccode = nbc.Spbccode;
                            string spbccodeName = nbc.SpbccodeName;
                            string nsumAmt = nbc.NsumAmt;
                            if (nsumAmt != null && nsumAmt != "")
                            {
                                messTask = "无签封出入库业务";
                                messInfo = "无签封出入库业务,任务总金额" + nsumAmt + "请刷卡开启栅栏门";
                            }

                            break;
                        case ("131076"):
                            messTask = "实物交接业务";
                            //if (handoverFlag)
                            //{
                            //    for (int i = 0; i < ipArrs.Length; i++)
                            //    {
                            //        string ip = ipArrs[i];
                            //        List<String> list = readerMJ.mjEpcData(ip);
                            //        LogHelper.Debug("门架缓存" + list.Count);
                            //        Thread.Sleep(1500);
                            //        if (!ip.Equals("127.0.0.1"))
                            //        {
                            //            bool flag = readerMJ.mjTurnOn(ip);
                            //            if (!flag)
                            //            {
                            //                turnOnFlag = false;
                            //            }
                            //            LogHelper.Debug("门架" + ip + "启动状态" + flag);
                            //        }

                            //    }
                            //    flagUser = true;
                            //}


                            break;

                        case ("65537"):
                            messInfo = "库内封装业务，请刷卡开启栅栏门";
                            messTask = "库内封装";

                            break;
                        case ("131080"):
                            messInfo = "库内封装业务，请刷卡开启栅栏门";
                            messTask = "库内封装";

                            break;
                    }
                    if (mustOutSack)
                    {
                        messInfo = messInfo + ",当前业务包含必出箱，请优先出必出箱";
                    }



                    LogHelper.Debug("下发到门架数据" + dataToPDAFinal);

                    bc = new BaseCommand();
                    bc.Code = int.Parse(code);

                    if (cardHash1.Count > 0) { cardHash1.Clear(); }
                    if (cardHash2.Count > 0) { cardHash2.Clear(); }
                    if (cardHash3.Count > 0) { cardHash3.Clear(); }
                    myCol.Clear();
                    flagGate = true;
                    flagMJ = true;
                    LogHelper.Debug("当前业务" + messTask);
                    ltTaskInfo.WriteMessage("当前业务:" + messTask);
                    ltScreenInfo.WriteMessage(messInfo);
                    


                }
                else
                {
                    ltScreenInfo.WriteMessage("未识别psam卡");
                }
            }
            catch (Exception e)
            {
                LogHelper.Debug("执行出错" + e);
            }
        }





        private void OCXTest_CardStateEvent(bool cardstate)
        {
            //Console.Out.WriteLine("卡状态" + cardstate);
            //throw new NotImplementedException();
        }






        bool selfNetConn = false;
        int sacnError = 0;
        //string scanEpc = "";
        //门架扫描
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {


                //收到2005后若没有刷卡登陆则提示刷卡登陆
                if (!flagLoginUser && flagPrompt&& !loginUser)
                {
                    ltScreenInfo.WriteMessage("请刷卡登陆");
                  
                }
               
               

                //门架启动前确保已收到任务，刷卡开启栅栏门，用户已登陆
                //if (flagMJ == true&& flagUser==true&& flagLoginUser==true)
                if (flagMJ == true && flagUser == true && flagLoginUser == true)
                //if (flagMJ == true  )
                {


                    LogHelper.Debug("门架开始扫描");
                    string[] ipArr = ipAll.Split(':');

                    for (int i = 0; i < ipArr.Length; i++)
                    {
                        string ip = ipArr[i];
                        if (ip.Length > 5 && !ip.Equals("127.0.0.1"))
                        {
                            bool mjStatus = readerMJ.getMjStatus(ip);
                            LogHelper.Debug("门架状态" + ip + mjStatus);
                            
                            
                            List<String> list = readerMJ.mjEpcData(ip);
                          
                           
                            list.ForEach(o => epcList.Add(o));

                            LogHelper.Debug("list" + list.Count);
                        }

                    }
                    if (epcList.Count > 0)
                    {


                        int code = bc.Code;
                        LogHelper.Debug("下发code为" + code);
                        if (code == 131075)
                        {
                            //入库
                            epcReal = new List<enterScanPackInfo>();
                            esd = new EnterScanData();
                            esd.Code = 163843;

                            int shiji = 0;
                            string epcData = "";

                            long moneyReality = 0;

                            foreach (string item in epcList)
                            {

                                //LogHelper.Debug("item" + item);
                                if (item.Length == 24)
                                {

                                    UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                                    string tag = ted.Tagid.ToString();
                                   
                                    if (epcDataPlan.Contains(tag) && ted.Tagid > 805843889)
                                    {

                                       
                                       
                                            //bool lockStatu = ted.Lockstuts;

                                            if (ted.Lockstuts && !ted.LockeEx)
                                            {                                               
                                                        //epcData = epcData + item + "|";
                                                        foreach (paymentSack ps in esc.PaymentSackList)
                                                        {

                                                            string sackNo = ps.SackNo;

                                                            if (tag.Equals(sackNo))
                                                            {

                                                                //scanEpc = scanEpc + tag;
                                                                shiji++;
                                                                enterScanPackInfo espi = new enterScanPackInfo();
                                                                epcData = epcData + tag + ":" + ps.VoucherTypeName + ":" + ps.PaperTypeName + "|";
                                                                espi.SackNo = tag;
                                                                espi.VoucherTypeID = ps.VoucherTypeID;
                                                                espi.VoucherTypeName = ps.VoucherTypeName;
                                                                espi.PaperTypeID = ps.PaperTypeID;
                                                                espi.PaperTypeName = ps.PaperTypeName;
                                                                espi.Val = ps.Val;
                                                                espi.Bundles = ps.Bundles;
                                                                espi.Tie = ps.Tie;
                                                                espi.SackMoney = ps.SackMoney;
                                                                espi.OprDT = DateTime.Now.ToString("yyyyMMddhhmmss");
                                                                espi.SstackCode = stackCode;
                                                                espi.SstackName = stackName;
                                                                epcReal.Add(espi);
                                                                moneyReality = moneyReality + long.Parse(ps.SackMoney.Split('.')[0]);
                                                                notScanList.Remove(tag);
                                                            }

                                                        }
                                                  
                                            }
                                            else
                                            {
                                                errorList.Add(item);
                                            }

                               

                                    }
                                    else if (ted.Tagid > 805843890)
                                    {
                                        notTaskList.Add(item);

                                    }
                                }

                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);
                                epcDataResult = epcData;
                            }
                            int shengyu = jihua - shiji;
                            long moneySurplus = moneyPlan - moneyReality;
                            string moneyPlanStr = moneyPlan.ToString("N");
                            string moneyRealityStr = moneyReality.ToString("N");
                            string moneySurplusStr = moneySurplus.ToString("N");
                            ltScreen.WriteClear();
                            ltScreen.WriteLineNoTime("[03]任务总金额[03]" + moneyPlanStr.Substring(0, moneyPlanStr.Length - 3) + "[03]元");
                            ltScreen.WriteLineNoTime("[01]已扫描金额[01]" + moneyRealityStr.Substring(0, moneyRealityStr.Length - 3) + "[01]元");
                            ltScreen.WriteLineNoTime("[07]剩余金额[07]" + moneySurplusStr.Substring(0, moneySurplusStr.Length - 3) + "[07]元");
                            ltScreen.WriteLineNoTime("[01]任务总袋数[01]" + jihua + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + shiji + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]剩余袋数[01]" + shengyu + "[01]袋数");
                            ltScreen.WriteLineNoTime(epcData);
                            //ftp.Upload(oneFile, "1.txt");
                            //确保已开启栅栏门
                            if (jihua == shiji && flagUser)
                            {
                                Thread.Sleep(1000);

                                LogHelper.Debug("计划" + jihua + "实际" + shiji);
                                esd.PackInfoList = epcReal.ToArray();
                                var serializerSettings = new JsonSerializerSettings
                                {
                                    // 设置为驼峰命名
                                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                                };
                                string json = JsonConvert.SerializeObject(esd, Newtonsoft.Json.Formatting.None, serializerSettings);

                                byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                socketClientMJ.sendAsynchronous(data);
                                //flagMJ = false;
                                epcReal.Clear();
                                bc.Code = 111;
                                //epcList.Clear();
                            }
                            else
                            {
                                LogHelper.Debug("计划" + jihua + "实际" + shiji);
                            }



                        }
                        else if (code == 131074)
                        {
                            //出库

                            osd = new OutScanData();
                            osd.Code = 163842;

                            if (version.Equals("1.0.3"))
                            {
                                osd.Error = "";
                            }
                            epcOut = new List<transferData>();

                            // int moneyTotal = 0;
                            long moneySacn = 0;
                            int shiji = 0;
                            // string valTotal = "";
                            string epcData = "";
                            long moneyTotal = 0;

                            jihua = 0;
                            osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                            foreach (outScanBusiInfo osb in osc.BusiInfoList)
                            {
                                string totalMoney = osb.TotalMoney.Split('.')[0];
                                string val = osb.Val;
                                Console.WriteLine("haveBoxInfo" + osb.HaveBoxInfo);
                                
                                int haveBoxInfo = osb.HaveBoxInfo;

                                if (haveBoxInfo == 0)
                                {
                                    moneyTotal = moneyTotal + long.Parse(totalMoney);
                                    jihua = (int)(jihua + long.Parse(totalMoney) / (long.Parse(val.Split('.')[0]) * 20000));

                                    LogHelper.Debug("val" + val + "totalMoney" + totalMoney);
                                }
                                


                            }



                            foreach (string item in epcList)
                            {
                                LogHelper.Debug("item" + item);
                                if (item.Length == 24)
                                {
                                    UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));

                                    int k = 0;
                                    if (ted.Tagid > 805843889)
                                    {
                                        string val = ValHelper.getVal(ted.Pervalueid.ToString());

                                        LogHelper.Debug("val" + val);
                                        string tag = ted.Tagid.ToString();
                                        if (sackMap.ContainsKey(tag))
                                        {

                                            string varcher = sackMap[tag];

                                            //bool lockStatu = epc.Substring(epcLength, 2).Equals("34");
                                            //epcData = epcData + item + "|";
                                            if (ted.Lockstuts && !ted.LockeEx)
                                            {

                                                //出库详情
                                                foreach (outScanStockPackInfo ossp in osc.StockPackInfoList)
                                                {

                                                    string sackNo = ossp.SackNo;
                                                    long scanMoney = long.Parse(ossp.SackMoney.Split('.')[0]);
                                                    //LogHelper.Debug("sackNo" + sackNo + "tag" + tag);

                                                    //满足扫描包号在出库列表中
                                                    if (tag.Equals(sackNo))
                                                    {
                                                        foreach (outScanBusiInfo osb in osc.BusiInfoList)
                                                        {
                                                            //满足扫描包号在出库任务券别中
                                                            int totalMoney = int.Parse(osb.TotalMoney.Split('.')[0]);
                                                            LogHelper.Debug("剩余总金额" + totalMoney);
                                                            if (osb.VoucherTypeID.Equals(varcher) && osb.HaveBoxInfo == 0 && totalMoney > 0)
                                                            {

                                                                shiji++;
                                                                //scanEpc = scanEpc + scanEpc;
                                                                osb.TotalMoney = Convert.ToString(totalMoney - scanMoney);
                                                                //moneySacn = k * money;
                                                                moneySacn = moneySacn + scanMoney;
                                                                transferData tfd = new transferData();
                                                                tfd.SackNo = tag;
                                                                tfd.VoucherTypeID = ossp.VoucherTypeID;
                                                                tfd.VoucherTypeName = ossp.VoucherTypeName;
                                                                tfd.PaperTypeID = ossp.PaperTypeID;
                                                                tfd.PaperTypeName = ossp.PaperTypeName;
                                                                tfd.Val = ossp.Val;
                                                                tfd.Bundles = ossp.Bundles;
                                                                tfd.Tie = ossp.Tie;
                                                                tfd.SackMoney = ossp.SackMoney;
                                                                tfd.MustOutFlag = ossp.MustOutFlag;
                                                                tfd.OprDT = DateTime.Now.ToString("yyyyMMddhhmmss");
                                                                tfd.StackCode = ossp.SstackCode;
                                                                epcOut.Add(tfd);
                                                                epcData = epcData + tag + ":" + ossp.VoucherTypeName + ":" + ossp.PaperTypeName + "|";


                                                                LogHelper.Debug("券别" + osb.Val + "总计" + shiji);
                                                                break;

                                                            }

                                                        }

                                                    }


                                                    }

                                                }

                                            }
                                            else
                                            {
                                                errorList.Add(item);

                                            }
                                        }
                                        else
                                        {

                                            notTaskList.Add(item);

                                        }
                                    
                                }
                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);
                                epcDataResult = epcData;

                            }
                            string moneyTotalStr = moneyTotal.ToString("N");
                            string moneySacnStr = moneySacn.ToString("N");
                            string moneySurplusStr = (moneyTotal - moneySacn).ToString("N");
                            int shengyu = jihua - shiji;
                            ltScreen.WriteClear();
                            ltScreen.WriteLineNoTime("[03]任务总金额[03]" + moneyTotalStr.Substring(0, moneyTotalStr.Length - 3) + "[03]元");
                            ltScreen.WriteLineNoTime("[01]已扫描总金额[01]" + moneySacnStr.Substring(0, moneySacnStr.Length - 3) + "[01]元");
                            ltScreen.WriteLineNoTime("[07]剩余总金额[07]" + moneySurplusStr.Substring(0, moneySurplusStr.Length - 3) + "[07]元");
                            ltScreen.WriteLineNoTime("[01]任务总袋数[01]" + jihua + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + shiji + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]剩余袋数[01]" + shengyu + "[01]袋数");
                            ltScreen.WriteLineNoTime(epcData);
                            //ftp.Upload(oneFile, "1.txt");
                            //Console.WriteLine("moneyTotal" + moneyTotal + "moneySacn" + moneySacn);
                            //确保已开启栅栏门
                            if (moneyTotal == moneySacn && flagUser == true)
                            {
                                osd.TransferDataList = epcOut.ToArray();
                                var serializerSettings = new JsonSerializerSettings
                                {
                                    // 设置为驼峰命名
                                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                                };
                                string json = JsonConvert.SerializeObject(osd, Newtonsoft.Json.Formatting.None, serializerSettings);

                                byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                socketClientMJ.sendAsynchronous(data);
                                //flagMJ = false;
                                epcOut.Clear();
                                //scanEpc = "";
                                //epcList.Clear();
                                bc.Code = 111;
                            }

                        }
                        else if (code == 131073)
                        {
                            //空包袋登记
                            SuperScanCMD ssc = new SuperScanCMD();
                            ssc = (SuperScanCMD)JsonConvert.DeserializeObject<SuperScanCMD>(dataToPDAFinal);

                            string epcData = "";
                            int scanCount = 0;
                            //序列化空包袋登记上送指令
                            ssd = new SuperScanData();
                            ssd.Code = 163841;

                            if (version.Equals("1.0.3"))
                            {
                                ssd.Error = "";
                            }
                            ssdList = new List<superScanPackinfo>();
                            foreach (string item in epcList)
                            {
                                if (item.Length == 24)
                                {
                                    Console.WriteLine("item===" + item);
                                    UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));


                                    if (ted.Tagid > 805843890)
                                    {

                                        string tag = ted.Tagid.ToString();
                                        string val = ValHelper.getVal(ted.Pervalueid.ToString());
                                        LogHelper.Debug("val" + val);
                                        //扫描券别在任务列表，且处于开袋状态
                                        if (checkVal(val, dataToPDAFinal))
                                        {
                                            scanCount++;
                                            superScanPackinfo ossp = new superScanPackinfo();

                                            ossp.Val = val + ".00";
                                            ossp.SackNo = tag;
                                            ossp.VoucherTypeID = newVoucherTypeID;
                                            ossp.VoucherTypeName = newVoucherTypeName;
                                            ossp.StackCode = stackCode;

                                            ossp.OprDT = DateTime.Now.ToString("yyyyMMddHHmmss");
                                            ssdList.Add(ossp);
                                            epcData = tag + ":" + newVoucherTypeName + "|";
                                        }


                                    }
                                }

                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);
                                if (commmitFlag)
                                {
                                    if (ssdList != null && ssdList.Count > 0)
                                    {
                                        ssd.PackInfoList = ssdList.ToArray();
                                        var serializerSettings = new JsonSerializerSettings
                                        {
                                            // 设置为驼峰命名
                                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                                        };
                                        string json = JsonConvert.SerializeObject(ssd, Newtonsoft.Json.Formatting.None, serializerSettings);

                                        byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                        socketClientMJ.sendAsynchronous(data);
                                        //ssdList.Clear();
                                        epcList.Clear();
                                    }
                                }
                            }
                            ltScreen.WriteClear();
                            ltScreen.WriteLineNoTime("[03]任务总金额[03]0[03]元");
                            ltScreen.WriteLineNoTime("[01]已扫描总金额[01]0[01]元");
                            ltScreen.WriteLineNoTime("[07]剩余总金额[07]0[07]元");
                            ltScreen.WriteLineNoTime("[01]任务描袋数[01]0[01]袋数");
                            ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + scanCount + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]剩余描袋数[01]0[01]袋数");
                            ltScreen.WriteLineNoTime(epcData);



                        }
                        else if (code == 131076)
                        {
                            //实物交接
                            //解析下发指令
                            if (handoverFlag)
                            {
                                TransferCMD tc = new TransferCMD();
                                tc = (TransferCMD)JsonConvert.DeserializeObject<TransferCMD>(dataToPDAFinal);
                                int totalMoney = 0;
                                int jihua = 0;
                                int shiji = 0;
                                int scanCount = 0;
                                foreach (outDetail od in tc.OutDetailList)
                                {
                                    int scanMoney = int.Parse(od.TotalMoney.Split('.')[0]);
                                    jihua = jihua + scanMoney;

                                }

                                LogHelper.Debug("任务总金额" + totalMoney);
                                string epcData = "";
                                //回送指令
                                ttd = new TransferTransferData();
                                ttd.Code = 163844;

                                if (version.Equals("1.0.3"))
                                {
                                    ttd.Error = "";
                                }

                                epcHandover = new List<transferPackInfo>();

                                foreach (string item in epcList)
                                {
                                    if (item.Length == 24)
                                    {
                                        UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                                        if (ted.Tagid > 805843890)
                                        {
                                            epcData = epcData + item + "|";
                                            string tag = ted.Tagid.ToString();
                                            foreach (scanSort ss in tc.ScanSortList)
                                            {
                                                if (tag.Equals(ss.SackNo))
                                                {
                                                    string bankCode = "";
                                                    string bankName = "";

                                                    foreach (outDetail od in tc.OutDetailList)
                                                    {
                                                        if (ss.VoucherTypeID.Equals(od.VoucherTypeID))
                                                        {
                                                            bankCode = od.OrganID;
                                                            bankName = od.OrganName;
                                                        }
                                                    }

                                                    scanCount++;
                                                    shiji = shiji + int.Parse(ss.SackMoney.Split('.')[0]);
                                                    //totalMoney = totalMoney - int.Parse(ss.SackMoney.Split('.')[0]);
                                                    transferPackInfo tpi = new transferPackInfo();
                                                    tpi.SackNo = tag;
                                                    tpi.SackMoney = ss.SackMoney;
                                                    tpi.PaperTypeID = ss.PaperTypeID;
                                                    tpi.PaperTypeName = ss.PaperTypeName;
                                                    tpi.Val = ss.Val;
                                                    tpi.VoucherTypeID = ss.VoucherTypeID;
                                                    tpi.VoucherTypeName = ss.VoucherTypeName;
                                                    tpi.OprDT = DateTime.Now.ToString("yyyyMMddHHmmss");
                                                    tpi.Bundles = ss.Bundles;
                                                    tpi.EditionCode = "";
                                                    tpi.EditionName = "";
                                                    tpi.BankCode = bankCode;
                                                    tpi.BankName = bankName;
                                                    epcHandover.Add(tpi);



                                                }
                                            }
                                        }
                                    }
                                }
                                if (epcData.Length > 2)
                                {
                                    epcData = epcData.Substring(0, epcData.Length - 1);

                                }
                                ltScreen.WriteClear();
                                ltScreen.WriteLineNoTime("[03]任务总金额[03]" + jihua + "[03]元");
                                ltScreen.WriteLineNoTime("[01]已扫描总金额[01]" + shiji + "[01]元");
                                ltScreen.WriteLineNoTime("[07]剩余总金额[07]" + (jihua - shiji) + "[07]元");
                                ltScreen.WriteLineNoTime("[01]任务总袋数[01]" + scanCount + "[01]袋数");
                                ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + scanCount + "[01]袋数");
                                ltScreen.WriteLineNoTime("[01]剩余袋数[01]" + scanCount + "[01]袋数");
                                ltScreen.WriteLineNoTime(epcData);
                                //ftp.Upload(oneFile, "1.txt");
                                if (jihua == shiji)
                                {
                                    ttd.PackInfoList = epcHandover.ToArray();
                                    var serializerSettings = new JsonSerializerSettings
                                    {
                                        // 设置为驼峰命名
                                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                                    };
                                    string json = JsonConvert.SerializeObject(ttd, Newtonsoft.Json.Formatting.None, serializerSettings);

                                    byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                    socketClientMJ.sendAsynchronous(data);
                                    flagMJ = false;
                                    epcHandover.Clear();
                                }

                            }

                        }

                        else if (code == 131080)
                        {
                            //空电子签封入库
                            EmptyPackCheckInCMD epci = new EmptyPackCheckInCMD();
                            epci = (EmptyPackCheckInCMD)JsonConvert.DeserializeObject<EmptyPackCheckInCMD>(dataToPDAFinal);
                            emptyPackInfoList = new List<emptyPackInfo>();
                            string epcData = "";
                            //回送指令
                            epcid = new EmptyPackCheckInData();
                            epcid.Code = 163848;
                            int scanCount = 0;
                            int shiji = 0;
                            int jihua = epci.PackInfoList.Length;


                            //获取库间信息
                            //foreach (stackInfo ss in epci.StackInfoList)
                            //{
                            //    stackCode = ss.SstackCode;
                            //    stackName = ss.SstackName;
                            //}
                            foreach (string item in epcList)
                            {

                                UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                                if (item.Length == 24)
                                {
                                    //epcData = epcData + item + "|";
                                    string tag = ted.Tagid.ToString();
                                    foreach (packInfo ss in epci.PackInfoList)
                                    {
                                        if (tag.Equals(ss.SackNo))
                                        {

                                            shiji++;

                                            emptyPackInfo tpi = new emptyPackInfo();
                                            tpi.SackNo = tag;

                                            tpi.Val = ss.Val;
                                            tpi.VoucherTypeID = ss.VoucherTypeID;
                                            tpi.VoucherTypeName = ss.VoucherTypeName;

                                            emptyPackInfoList.Add(tpi);
                                            epcData = epcData + ":" + ss.VoucherTypeName + "|";

                                        }
                                    }
                                }
                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);

                            }


                            ltScreen.WriteClear();
                            ltScreen.WriteLineNoTime("[03]任务总金额[03]0[03]元");
                            ltScreen.WriteLineNoTime("[01]已扫描金额[01]0[01]元");
                            ltScreen.WriteLineNoTime("[07]剩余金额[07]0[07]元");
                            ltScreen.WriteLineNoTime("[01]任务总袋数[01]" + jihua + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + shiji + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]剩余袋数[01]" + (jihua - shiji) + "[01]袋数");
                            ltScreen.WriteLineNoTime(epcData);
                            if (jihua == shiji && jihua > 0)
                            {
                                epcid.PackInfoList = emptyPackInfoList.ToArray();
                                var serializerSettings = new JsonSerializerSettings
                                {
                                    // 设置为驼峰命名
                                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                                };
                                string json = JsonConvert.SerializeObject(epcid, Newtonsoft.Json.Formatting.None, serializerSettings);

                                byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                socketClientMJ.sendAsynchronous(data);
                                //flagMJ = false;
                                emptyPackInfoList.Clear();
                            }

                        }
                        else if (code == 131081)
                        {
                            //电子签封入库核对
                            CheckInCMD cc = new CheckInCMD();
                            cc = (CheckInCMD)JsonConvert.DeserializeObject<CheckInCMD>(dataToPDAFinal);
                            string epcData = "";
                            //回送指令
                            cidd = new CheckInData();
                            cidd.Code = 163849;
                            int scanCount = 0;
                            int shiji = 0;
                            int jihua = 0;
                            int scanPlan = cc.CheckInList.Length;
                            //获取总金额
                            foreach (packinfoCheck ss in cc.CheckInList)
                            {
                                jihua = jihua + int.Parse(ss.SackMoney.Split('.')[0]); ;
                            }
                            foreach (string item in epcList)
                            {
                                if (item.Length == 24)
                                {
                                    UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                                    if (ted.Tagid > 805843890)
                                    {
                                        //epcData = epcData + item + "|";
                                        string tag = ted.Tagid.ToString();
                                        foreach (packinfoCheck ss in cc.CheckInList)
                                        {
                                            if (tag.Equals(ss.SackNo))
                                            {

                                                scanCount++;
                                                shiji = shiji + int.Parse(ss.SackMoney.Split('.')[0]);
                                                //totalMoney = totalMoney - int.Parse(ss.SackMoney.Split('.')[0]);
                                                packInfoCheck tpi = new packInfoCheck();
                                                tpi.SackNo = tag;
                                                tpi.SackMoney = ss.SackMoney;
                                                tpi.PaperTypeID = ss.PaperTypeID;
                                                tpi.PaperTypeName = ss.PaperTypeName;
                                                tpi.Val = ss.Val;
                                                tpi.VoucherTypeID = ss.VoucherTypeID;
                                                tpi.VoucherTypeName = ss.VoucherTypeName;
                                                tpi.OprDT = DateTime.Now.ToString("yyyyMMddHHmmss");
                                                tpi.Bundles = ss.Bundles;
                                                tpi.SstackCode = ss.SstackCode;
                                                tpi.SstackName = ss.SstackName;
                                                packInfoCheckList.Add(tpi);
                                                epcData = tag + ":" + ss.VoucherTypeName + ":" + ss.PaperTypeName + "|";

                                            }
                                        }
                                    }
                                }
                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);

                            }


                            ltScreen.WriteClear();
                            ltScreen.WriteLineNoTime("[03]任务总金额[03]" + jihua + "[03]元");
                            ltScreen.WriteLineNoTime("[01]已扫描金额[01]" + shiji + "[01]元");
                            ltScreen.WriteLineNoTime("[07]剩余金额[07]" + (jihua - shiji) + "[07]元");
                            ltScreen.WriteLineNoTime("[01]任务总袋数[01]" + scanPlan + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + scanCount + "[01]袋数");
                            ltScreen.WriteLineNoTime("[01]剩余袋数[01]" + (scanPlan - scanCount) + "[01]袋数");
                            ltScreen.WriteLineNoTime(epcData);
                            if (jihua == shiji)
                            {
                                cidd.PackInfoList = packInfoCheckList.ToArray();
                                var serializerSettings = new JsonSerializerSettings
                                {
                                    // 设置为驼峰命名
                                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                                };
                                string json = JsonConvert.SerializeObject(cidd, Newtonsoft.Json.Formatting.None, serializerSettings);

                                byte[] data = CommondHelper.DataCommit(taskIdSend, sequence, "4002", "11", json, operatorUser, auditorUser);
                                socketClientMJ.sendAsynchronous(data);
                                //flagMJ = false;
                                packInfoCheckList.Clear();
                            }

                        }
                        else if (code == 111)
                        {
                            string epcData = "";
                            int shiji = 0;
                            foreach (string item in epcList)
                            {
                                if (item.Length == 24)
                                {
                                    UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                                    if (ted.Tagid > 805843890)
                                    {
                                        notTaskList.Add(item);
                                        shiji++;
                                        epcData = ted.Tagid.ToString() + ":" + ted.Pervalueid.ToString() + "|";

                                    }

                                }
                            }
                            if (epcData.Length > 2)
                            {
                                epcData = epcData.Substring(0, epcData.Length - 1);
                                ltScreen.WriteClear();
                                ltScreen.WriteLineNoTime("[03]任务总金额[03]0[03]元");
                                ltScreen.WriteLineNoTime("[01]已扫描金额[01]0[01]元");
                                ltScreen.WriteLineNoTime("[07]剩余金额[07]0[07]元");
                                ltScreen.WriteLineNoTime("[01]任务总袋数[01]0[01]袋数");
                                ltScreen.WriteLineNoTime("[01]已扫描袋数[01]" + shiji + "[01]袋数");
                                ltScreen.WriteLineNoTime("[01]剩余袋数[01]0[01]袋数");
                                ltScreen.WriteLineNoTime(epcData);

                            }




                        }
                    }
            }
            }
            catch (Exception ex)
            {
                LogHelper.Debug("门架扫描出错" + ex);
            }


}


        static string newVoucherTypeID = "";
        static string newVoucherTypeName = "";
        static string newVal = "";
        public static Boolean checkVal(string val,string dataToPDAFinal)
        {
            try
            {
                SuperScanCMD ssc = new SuperScanCMD();
                //string dataToPDAFinal = ltTaskCmd.ReadMessage();

                ssc = (SuperScanCMD)JsonConvert.DeserializeObject<SuperScanCMD>(dataToPDAFinal);
                foreach (superScanBusiInfo ssbi in ssc.BusiInfoList)
                {
                    if (ssbi.Val.Contains(val))
                    {
                        newVoucherTypeID = ssbi.VoucherTypeID;
                        newVoucherTypeName = ssbi.VoucherTypeName;
                        newVal = ssbi.Val;

                        return true;

                    }
                }
               
            }
            catch (Exception e)
            {
                LogHelper.Debug("授权开启栅栏门失败" + e);
            }
            return false;
        }



        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                
                //string id = ltSstackCode.ReadMessage();
                List<StackCode> scList = new List<StackCode>();
                //StackCode sc = new StackCode();
                //sc.Id = stackCode;
                List<string> list = new List<string>();
                list.Add(stackCode);
                StackCodeList scl = new StackCodeList();
                scl.Code = 163847;


                scl.Stacks = list;

                var serializerSettings = new JsonSerializerSettings
                {
                    // 设置为驼峰命名
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                string json = JsonConvert.SerializeObject(scl, Newtonsoft.Json.Formatting.None, serializerSettings);

                byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                socketClientMJ.sendAsynchronous(data);
                flagMJ = false;
            }
            catch (Exception ex)
            {
                LogHelper.Debug("提交出错" + ex);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
             
                
                //待办业务
                if (toDealFlag)
                {
                    dataToPDAFinal = ltTaskCmd.ReadMessage();                    
                    if (dataToPDAFinal=="") 
                    {
                        string readId = ltid.ReadMessage();
                        LogHelper.Debug("脱机存储id" + readId);
                        TXTHelper taskRead = new TXTHelper(readId + "TaskCmd");
                        dataToPDAFinal = taskRead.ReadMessage();
                    }
                    LogHelper.Debug("待办业务" + dataToPDAFinal);

                    if (dataToPDAFinal.Length > 0)
                    {

                        comCom(yellowOff);
                        comCom(greenOn);
                        epcList.Clear();
                        flagUser = false;
                        errorList.Clear();
                        notTaskList.Clear();

                        JObject jo = JObject.Parse(dataToPDAFinal);
                        string code = jo["code"].ToString();
                        LogHelper.Debug("下发code为" + code);
                        string messInfo = "";
                        string messTask = "";
                        epcDataPlan = "";
                        mustOutSack = false;
                        switch (code)
                        {
                            case ("131074"):
                                sackMap.Clear();
                                messInfo = "出库业务，请刷卡开启栅栏门";
                                messTask = "出库业务";
                                //stackCode = ((JArray)jo["stockPackInfoList"])[0]["sstackCode"].ToString();
                                //osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                                osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                                foreach (outScanStockPackInfo ossp in osc.StockPackInfoList)
                                {
                                    string sackNo = ossp.SackNo;
                                    string voucherTypeID = ossp.VoucherTypeID;
                                    string mustOutFlag = ossp.MustOutFlag;
                                    epcDataPlan = epcDataPlan + sackNo + ":";
                                    sackMap.Add(sackNo, voucherTypeID);
                                    if (mustOutFlag.Equals("1"))
                                    {
                                        mustOutSack = true;
                                        mustSackNo = mustSackNo + sackNo + ":";
                                    }

                                }
                               
                                break;
                            case ("131075"):
                                messInfo = "入库业务，请刷卡开启栅栏门";
                                messTask = "入库业务";
                                //stackCode = ((JArray)jo["stackInfoList"])[0]["sstackCode"].ToString();
                                esc = (EnterScanCMD)JsonConvert.DeserializeObject<EnterScanCMD>(dataToPDAFinal);
                                moneyPlan = 0;
                                notScanList.Clear();
                                //遍历计划内的锁条号和金额
                                foreach (paymentSack ps in esc.PaymentSackList)
                                {
                                    string sackNo = ps.SackNo;
                                    string sackMoney = ps.SackMoney;
                                    moneyPlan = moneyPlan + long.Parse(sackMoney.Split('.')[0]);
                                    epcDataPlan = epcDataPlan + sackNo + ":";
                                    notScanList.Add(sackNo);
                                }
                              
                                jihua = esc.PaymentSackList.Length;
                                break;
                            case ("131078"):
                                messInfo = "日核对业务，请刷卡开启栅栏门";
                                messTask = "日核对业务";
                                //stackCode = ((JArray)jo["stockList"])[0]["sstackCode"].ToString();
                                //DailyCheckCMD dcc = (DailyCheckCMD)JsonConvert.DeserializeObject<DailyCheckCMD>(dataToPDAFinal);
                                //ArrayList dailyCheckStackCodeList = new ArrayList();
                                //foreach (stockCheck sc in dcc.StockList)
                                //{
                                //    stackCode = sc.SstackCode;
                                //    stackName = sc.SstackName;
                                //    dailyCheckStackCodeList.Add(new DictionaryEntry(stackName, stackCode));
                                //}

                                //comboBox1.DataSource = removeDuplicate(dailyCheckStackCodeList);
                                //comboBox1.DisplayMember = "Key";//显示出来的。Text

                                //comboBox1.ValueMember = "Value";// value值。
                                //this.comboBox1.SelectedIndex = 0;
                                break;
                            case ("131073"):
                                messInfo = "空包袋登记业务，如需进库请刷卡开启栅栏门";
                                messTask = "空包袋登记业务";
                                //sstackCode = ((JArray)jo["stackInfoList"])[0]["sstackCode"].ToString();
                                
                                flagUser = true;
                                
                                break;
                            case ("131079"):
                                messInfo = "非业务进出库，请刷卡开启栅栏门";
                                messTask = "非业务进出库";
                                //stackCode = ((JArray)jo["stacks"])[0]["id"].ToString();
                                LogHelper.Debug("库间名称" + stackCode + "意图" + ((JArray)jo["stacks"])[0]["intention"].ToString());
                                messInfo = messInfo + ((JArray)jo["stacks"])[0]["intention"].ToString();
                                NoBusinessCMD nbc = (NoBusinessCMD)JsonConvert.DeserializeObject<NoBusinessCMD>(dataToPDAFinal);
                                string spbccode = nbc.Spbccode;
                                string spbccodeName = nbc.SpbccodeName;
                                string nsumAmt = nbc.NsumAmt;
                                if (nsumAmt != null && nsumAmt != "")
                                {
                                    messTask = "无签封出入库业务";
                                    messInfo = "无签封出入库业务,任务总金额" + nsumAmt + "请刷卡开启栅栏门";
                                }
                                //遍历库间编号
                                //ArrayList noBusinessStackCodeList = new ArrayList();
                                //foreach (stackCode si in nbc.Stacks)
                                //{
                                //    stackCode = si.Id;
                                //    stackName = si.Name;
                                //    noBusinessStackCodeList.Add(new DictionaryEntry(stackName, stackCode));

                                //}

                                //comboBox1.DataSource = noBusinessStackCodeList;
                                //comboBox1.DisplayMember = "Key";//显示出来的。Text

                                //comboBox1.ValueMember = "Value";// value值。
                                //this.comboBox1.SelectedIndex = 0;
                                break;
                            case ("131076"):
                                messTask = "实物交接业务";
                                break;
                            case ("65537"):
                                messInfo = "库内封装业务，请刷卡开启栅栏门";
                                messTask = "库内封装";
                               
                                break;
                            case ("131080"):
                                messInfo = "库内封装业务，请刷卡开启栅栏门";
                                messTask = "库内封装";
                               
                                
                                break;
                        }
                        if (mustOutSack)
                        {
                            messInfo = messInfo + ",当前业务包含必出箱，请优先出必出箱";
                        }
                        ltScreenInfo.WriteMessage(messInfo);

                        LogHelper.Debug("当前业务" + messTask);
                        ltTaskInfo.WriteMessage("当前业务:" + messTask);
                        bool turnOnFlag = true;
                        string[] ipArrs = ipAll.Split(':');
                        for (int i = 0; i < ipArrs.Length; i++)
                        {
                            string ip = ipArrs[i];
                            List<String> list = readerMJ.mjEpcData(ip);
                            LogHelper.Debug("门架缓存" + list.Count);
                            Thread.Sleep(1500);
                            bool flag = readerMJ.mjTurnOn(ip);
                            if (!flag)
                            {
                                turnOnFlag = false;
                            }
                            LogHelper.Debug("门架" + ip + "启动状态" + flag);
                        }
                        if (turnOnFlag)
                        {
                            ltScreenInfo.WriteMessage("门架启动成功");
                        }
                        flagGate = true;

                        bc = new BaseCommand();
                        bc.Code = int.Parse(code);
                        flagMJ = true;
                      
                        

                    }
                }
                else
                {
                    ltScreenInfo.WriteMessage("尚未接入通讯组件，请稍后");
                }
               
            }
            catch (Exception ex)
            {
                LogHelper.Debug("===" + ex);
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {

           
            

            //非业务进出库
            try
            {

                List<StackCode> scList = new List<StackCode>();
                StackCode sc = new StackCode();
                sc.Id = stackCode;
                List<string> list = new List<string>();
                list.Add(stackCode);
                StackCodeList scl = new StackCodeList();
                scl.Code = 163847;


                scl.Stacks = list;



                var serializerSettings = new JsonSerializerSettings
                {
                    // 设置为驼峰命名
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                string json = JsonConvert.SerializeObject(scl, Newtonsoft.Json.Formatting.None, serializerSettings);

                byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                socketClientMJ.sendAsynchronous(data);
               // flagMJ = false;
               // flagGate = false;

            }
            catch (Exception ex)
            {
                LogHelper.Debug("提交出错" + ex);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                if (taskIdSend == "" || taskIdSend == null)
                {
                    taskIdSend = ltid.ReadMessage();
                }
                LogHelper.Debug("taskIdSend===" + taskIdSend);

                //空包袋登记手动提交
                if (ssdList != null && ssdList.Count > 0)
                {
                    ssd.PackInfoList = ssdList.ToArray();
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 设置为驼峰命名
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    string json = JsonConvert.SerializeObject(ssd, Newtonsoft.Json.Formatting.None, serializerSettings);

                    byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                    socketClientMJ.sendAsynchronous(data);
                    flagMJ = false;
                    //ssdList.Clear();
                }

                //入库手动提交
                if (epcReal != null && epcReal.Count > 0)
                {
                    esd.PackInfoList = epcReal.ToArray();
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 设置为驼峰命名
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    string json = JsonConvert.SerializeObject(esd, Newtonsoft.Json.Formatting.None, serializerSettings);
                    
                    
                    byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                    socketClientMJ.sendAsynchronous(data);
                    flagMJ = false;
                    //清空数据
                    epcReal.Clear();
                }
                //出库手动提交
                if (epcOut != null && epcOut.Count > 0)
                {
                    osd.TransferDataList = epcOut.ToArray();
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 设置为驼峰命名
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    string json = JsonConvert.SerializeObject(osd, Newtonsoft.Json.Formatting.None, serializerSettings);

                    byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                    socketClientMJ.sendAsynchronous(data);
                    flagMJ = false;
                    epcOut.Clear();
                }
                //实物交接手动提交
                if (epcHandover != null && epcHandover.Count > 0)
                {
                    ttd.PackInfoList = epcHandover.ToArray();
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 设置为驼峰命名
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    string json = JsonConvert.SerializeObject(ttd, Newtonsoft.Json.Formatting.None, serializerSettings);

                    byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                    socketClientMJ.sendAsynchronous(data);
                    flagMJ = false;
                    epcHandover.Clear();
                }
                //库内封装入库空包袋登记扫描
                if (emptyPackInfoList != null && emptyPackInfoList.Count > 0)
                {
                    epcid.PackInfoList = emptyPackInfoList.ToArray();
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 设置为驼峰命名
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    };
                    string json = JsonConvert.SerializeObject(epcid, Newtonsoft.Json.Formatting.None, serializerSettings);

                    byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                    socketClientMJ.sendAsynchronous(data);
                    flagMJ = false;
                    emptyPackInfoList.Clear();
                }
              
            }
            catch (Exception ex)
            {
                LogHelper.Debug("==" + ex);
            }
        }
        public void cbExceptionCB(uint dwType, int lUserID, int lHandle, IntPtr pUser)
        {
            //异常消息信息类型
            string stringAlarm = "异常消息回调，信息类型：0x" + Convert.ToString(dwType, 16) + ", lUserID:" + lUserID + ", lHandle:" + lHandle;


            //创建该控件的主线程直接更新信息列表 
            UpdateClientListException(DateTime.Now.ToString(), lUserID, stringAlarm);

        }

        public bool MsgCallback_V31(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);

            return true; //回调函数需要有返回，表示正常接收到数据
        }
        public void cbLoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
        {
            string strLoginCallBack = "登录设备，lUserID：" + lUserID + "，dwResult：" + dwResult;

            if (dwResult == 0)
            {
                uint iErrCode = CHCNetSDK.NET_DVR_GetLastError();
                strLoginCallBack = strLoginCallBack + "，错误号:" + iErrCode;
            }

            //下面代码注释掉也会崩溃

            //创建该控件的主线程直接更新信息列表 
            UpdateClientList(strLoginCallBack, lpDeviceInfo);

        }

        public void UpdateClientList(string strAlarmTime, string strDevIP, string strAlarmMsg)
        {
            //列表新增报警信息
            Console.WriteLine("strAlarmTime" + strAlarmTime + "strDevIP" + strDevIP + "strAlarmMsg" + strAlarmMsg);
        }

        public void UpdateClientList(string strLogStatus, IntPtr lpDeviceInfo)
        {
            //列表新增报警信息
            Console.WriteLine("登录状态（异步）：" + strLogStatus);
        }
        public void UpdateClientListException(string strAlarmTime, int lUserID, string strAlarmMsg)
        {
            //异常设备信息



            //列表新增报警信息
            Console.WriteLine(strAlarmTime, lUserID, strAlarmMsg);

        }
        public void AlarmMessageHandle(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            try
            {
                //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
                switch (lCommand)
                {

                    case CHCNetSDK.COMM_ALARM_ACS://门禁主机报警上传
                        ProcessCommAlarm_AcsAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                        break;


                    default:
                        {
                            //报警设备IP地址
                            string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');

                            //报警信息类型
                            string stringAlarm = "报警上传，信息类型：0x" + Convert.ToString(lCommand, 16);


                            //创建该控件的主线程直接更新信息列表 
                            UpdateClientList(DateTime.Now.ToString(), strIP, stringAlarm);

                        }
                        break;
                }
            }
            catch (Exception e)
            {
                LogHelper.Debug("==" + e);
            }
        }
        private void ProcessCommAlarm_AcsAlarm(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            try
            {
                CHCNetSDK.NET_DVR_ACS_ALARM_INFO struAcsAlarm = new CHCNetSDK.NET_DVR_ACS_ALARM_INFO();
                uint dwSize = (uint)Marshal.SizeOf(struAcsAlarm);
                struAcsAlarm = (CHCNetSDK.NET_DVR_ACS_ALARM_INFO)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_ACS_ALARM_INFO));

                //报警设备IP地址
                string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');

                //保存抓拍图片
                if ((struAcsAlarm.dwPicDataLen != 0) && (struAcsAlarm.pPicData != IntPtr.Zero))
                {
                    string str = ".\\picture\\Device_Acs_CapturePic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iFileNumber + ".jpg";
                    FileStream fs = new FileStream(str, FileMode.Create);
                    int iLen = (int)struAcsAlarm.dwPicDataLen;
                    byte[] by = new byte[iLen];
                    Marshal.Copy(struAcsAlarm.pPicData, by, 0, iLen);
                    fs.Write(by, 0, iLen);
                    fs.Close();
                    iFileNumber++;
                }

                //报警时间：年月日时分秒
                string strTimeYear = (struAcsAlarm.struTime.dwYear).ToString();
                string strTimeMonth = (struAcsAlarm.struTime.dwMonth).ToString("d2");
                string strTimeDay = (struAcsAlarm.struTime.dwDay).ToString("d2");
                string strTimeHour = (struAcsAlarm.struTime.dwHour).ToString("d2");
                string strTimeMinute = (struAcsAlarm.struTime.dwMinute).ToString("d2");
                string strTimeSecond = (struAcsAlarm.struTime.dwSecond).ToString("d2");
                string strTime = strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond;

                string stringAlarm = "门禁主机报警信息，dwMajor：0x" + Convert.ToString(struAcsAlarm.dwMajor, 16) + "，dwMinor：0x" +
                    Convert.ToString(struAcsAlarm.dwMinor, 16) + "，卡号：" + System.Text.Encoding.UTF8.GetString(struAcsAlarm.struAcsEventInfo.byCardNo).TrimEnd('\0')
                    + "，读卡器编号：" + struAcsAlarm.struAcsEventInfo.dwCardReaderNo + "，报警触发时间：" + strTime +
                    "，事件流水号：" + struAcsAlarm.struAcsEventInfo.dwSerialNo;
                LogHelper.Debug("===" + stringAlarm);

                //事件类型03操作  05事件
                string dwMajor = "0x" + Convert.ToString(struAcsAlarm.dwMajor, 16);
                string dwMinor = "0x" + Convert.ToString(struAcsAlarm.dwMinor, 16);
                string cardNum = System.Text.Encoding.UTF8.GetString(struAcsAlarm.struAcsEventInfo.byCardNo).TrimEnd('\0');
                LogHelper.Debug("人脸识别验证通过，卡号为" + cardNum + "ip为" + strIP);
                LogHelper.Debug("用户刷卡卡号" + cardAll);
                string[] deviceIpArr = deviceIp.Split(':');
                bool myColClear = false;
                if (dwMajor.Equals("0x5") && dwMinor.Equals("0x4b"))
                {

                    //管库员刷卡通过
                    if (openGateType == 1 && flagFace)
                    {
                        if (cardAll.Contains(cardNum))
                        {
                            
                            ltScreenInfo.WriteMessage("人脸识别验证通过，卡号为" + cardNum);
                            myCol.Add(strIP, cardNum);
                            foreach (string keys in myCol)
                            {
                                LogHelper.Debug(keys + ":" + myCol[keys]);
                                string[] cardArr = myCol[keys].Split(',');

                                foreach (string cardId in cardArr)
                                {
                                    int i = 0;
                                    foreach (string deviceIps in deviceIpArr)
                                    {
                                        if (keys.Equals(deviceIps) && i == 0)
                                        {
                                            cardHash1.Add(cardId);
                                            LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash1.Count);
                                            if (cardHash1.Count == userGateCount)
                                            {
                                                ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");

                                                myColClear = true;
                                                cardHash1.Clear();
                                                comComGate(gateOn);
                                                Thread.Sleep(gateTime);
                                                comCom(gateOff);
                                            }
                                        }
                                        else if (keys.Equals(deviceIps) && i == 1)
                                        {
                                            cardHash2.Add(cardId);
                                            LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash2.Count);
                                            if (cardHash2.Count == userGateCount)
                                            {
                                                ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");

                                                myColClear = true;
                                                cardHash2.Clear();
                                                comComGate(gateOn1);
                                                Thread.Sleep(gateTime);
                                                comCom(gateOff1);
                                            }
                                        }
                                        else if (keys.Equals(deviceIps) && i == 2)
                                        {
                                            cardHash3.Add(cardId);
                                            LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash3.Count);
                                            if (cardHash3.Count == userGateCount)
                                            {
                                                ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");

                                                myColClear = true;
                                                cardHash3.Clear();
                                                comComGate(gateOn2);
                                                Thread.Sleep(gateTime);
                                                comCom(gateOff2);
                                            }
                                        }
                                        i++;
                                    }

                                }
                            }
                        }
                        if (myColClear)
                        {
                            myCol.Clear();
                        }
                    }
                    else if(openGateType == 2 || openGateType==3)
                    {
                        if (userInfo.Contains(cardNum) && cardNum.Length > 0)
                        {

                            foreach (string item in userList)
                            {
                                LogHelper.Debug("item" + item);
                                //开启栅栏门刷卡用户且 收到入库指令
                                if (item.Contains(cardNum) && item.Contains("isolate") && flagGate)
                                {
                                    ltScreenInfo.WriteMessage("人脸识别验证通过，卡号为" + cardNum);
                                    myCol.Add(strIP, item.Split(':')[0]);
                                    foreach (string keys in myCol)
                                    {
                                        LogHelper.Debug(keys + ":" + myCol[keys]);
                                        string[] cardArr = myCol[keys].Split(',');

                                        foreach (string cardId in cardArr)
                                        {
                                            int i = 0;
                                            foreach (string deviceIps in deviceIpArr)
                                            {
                                                if (keys.Equals(deviceIps) && i == 0)
                                                {
                                                    cardHash1.Add(cardId);
                                                    LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash1.Count);
                                                    if (cardHash1.Count == userGateCount)
                                                    {
                                                        foreach (string res in cardHash1)
                                                        {
                                                            userGate = userGate + res + ",";
                                                        }
                                                        LogHelper.Debug("符合的用户" + userGate);
                                                        byte[] commond = CommondHelper.UserEmpower(stackCode, "4003", "11", userGate, userGateCount, sequence);
                                                        socketClientMJ.send(commond);
                                                        userGate = "";
                                                        ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");
                                                        myColClear = true;
                                                    }
                                                }
                                                else if (keys.Equals(deviceIps) && i == 1)
                                                {
                                                    cardHash2.Add(cardId);
                                                    LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash2.Count);
                                                    if (cardHash2.Count == userGateCount)
                                                    {
                                                        foreach (string res in cardHash2)
                                                        {
                                                            userGate = userGate + res + ",";
                                                        }
                                                        LogHelper.Debug("符合的用户" + userGate);
                                                        byte[] commond = CommondHelper.UserEmpower(stackCode, "4003", "11", userGate, userGateCount, sequence);
                                                        socketClientMJ.send(commond);
                                                        userGate = "";
                                                        ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");
                                                        myColClear = true;
                                                    }
                                                }
                                                else if (keys.Equals(deviceIps) && i == 2)
                                                {
                                                    cardHash3.Add(cardId);
                                                    LogHelper.Debug("人脸IP" + keys + "已验证" + cardHash3.Count);
                                                    if (cardHash3.Count == userGateCount)
                                                    {
                                                        foreach (string res in cardHash3)
                                                        {
                                                            userGate = userGate + res + ",";
                                                        }
                                                        LogHelper.Debug("符合的用户" + userGate);
                                                        byte[] commond = CommondHelper.UserEmpower(stackCode, "4003", "11", userGate, userGateCount, sequence);
                                                        socketClientMJ.send(commond);
                                                        userGate = "";
                                                        ltScreenInfo.WriteMessage("人脸识别验证通过，开启栅栏门");
                                                        myColClear = true;
                                                    }
                                                }
                                                i++;
                                            }

                                        }
                                    }
                                }

                               
                            }                          
                            
                        }

                        if (myColClear)
                        {
                            myCol.Clear();
                        }

                    }
               


            }
                else if (dwMinor.Equals("0x4c"))
                {
                    LogHelper.Debug("人脸识别验证失败");
                }

                if (struAcsAlarm.byAcsEventInfoExtendV20 == 1)
                {
                    CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND_V20 struInfoExtendV20 = new CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND_V20();
                    uint dwSizeEx = (uint)Marshal.SizeOf(struInfoExtendV20);
                    struInfoExtendV20 = (CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND_V20)Marshal.PtrToStructure(struAcsAlarm.pAcsEventInfoExtendV20, typeof(CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND_V20));
                    stringAlarm = stringAlarm + ", 温度:" + struInfoExtendV20.fCurrTemperature + ", 是否异常温度:" + struInfoExtendV20.byIsAbnomalTemperature
                        + ", 是否需要核验:" + struInfoExtendV20.byRemoteCheck;

                    if (struInfoExtendV20.byRemoteCheck == 2)
                    {
                        //ACS_remoteCheck(struAcsAlarm.struAcsEventInfo.dwSerialNo);
                        //下发核验结果命令，实际可以使用消息事件的方式在回调函数外面处理，避免这样直接处理阻塞回调
                    }

                    //保存热成像图片
                    if ((struInfoExtendV20.dwThermalDataLen != 0) && (struInfoExtendV20.pThermalData != IntPtr.Zero))
                    {
                        string str = ".\\picture\\Device_Acs_ThermalData_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iFileNumber + ".jpg";
                        FileStream fs = new FileStream(str, FileMode.Create);
                        int iLen = (int)struInfoExtendV20.dwThermalDataLen;
                        byte[] by = new byte[iLen];
                        Marshal.Copy(struInfoExtendV20.pThermalData, by, 0, iLen);
                        fs.Write(by, 0, iLen);
                        fs.Close();
                        iFileNumber++;
                    }
                }

                if (struAcsAlarm.byAcsEventInfoExtend == 1)
                {
                    CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND struInfoExtend = new CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND();
                    uint dwSizeEx = (uint)Marshal.SizeOf(struInfoExtend);
                    struInfoExtend = (CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND)Marshal.PtrToStructure(struAcsAlarm.pAcsEventInfoExtend, typeof(CHCNetSDK.NET_DVR_ACS_EVENT_INFO_EXTEND));
                    stringAlarm = stringAlarm + ", 人员类型:" + struInfoExtend.byUserType;
                }


                //创建该控件的主线程直接更新信息列表 
                UpdateClientList(DateTime.Now.ToString(), strIP, stringAlarm);

            }
            catch (Exception e)
            {
                LogHelper.Debug("人脸识别===" + e);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (epcDataResult.Length > 2)
            {
                string[] epcDataResultArr = epcDataResult.Split('|');
                string contentView = "已扫描袋号\r\n电子签封ID:券别";
                foreach(string item in epcDataResultArr)
                {
                    string sackNo = item.Split(':')[0];
                    string val = item.Split(':')[1];
                    contentView = contentView + sackNo + ":" + val+ "\r\n";
                }

                ltScreenInfo.WriteMessage(contentView);
            }

        }

       
        public static ListItem FindByText(ComboBox cmb, string strText)
        {
            foreach (ListItem li in cmb.Items)
            {
                if (li.Value == strText)
                {
                    return li;
                }
            }
            return null;
        }
        private void serialPort_DataReceivedEventHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           
            int len = this.serialPort2.BytesToRead;
            string receivedata = string.Empty;
            if (len != 0)
            {
                byte[] buff = new byte[len];
                this.serialPort2.Read(buff, 0, len);
                receivedata = HexUtils.byteToHexStr(buff);
            }
            
            LogHelper.Debug("receivedata" + receivedata);

           
           
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.Debug("手动连接通讯组件");
                socketClientMJ.soekctClose();
                socketClientMJ.conn();
            }
            catch (Exception ex)
            {

            }
            
            
            

        }

        private void button9_Click(object sender, EventArgs e)
        {
            //string epc = UserTool.EpcReader.readEpc(HexUtils.strToHexByte("478B3643164E20260008CEC1"));
           // epcList.Add("478B3643164E20260008CEC1");
            ltScreenInfo.WriteMessage("请刷卡解除警报" );
            //flagGate = true;
            flagAlarm = true;
           
            foreach (string item in errorList)
            {
                LogHelper.Debug("errorList" + item);
                epcList.Remove(item);
            }
            foreach (string item in notTaskList)
            {
                LogHelper.Debug("notTaskList" + item);
                epcList.Remove(item);
            }
            errorList.Clear();
            notTaskList.Clear();


        }

        private void timer2_Tick(object sender, EventArgs e)
        {
           
            try
            {
                if (heartStart&&heartStatu && socketSatau&& socketClientMJ.socketConn())
                {
                    byte[] dataHeart = CommondHelper.HeartConnect("0000", "11", "2");
                    socketClientMJ.send(dataHeart);
                }
                if (errorList.Count > 0|| notTaskList.Count>0)
                {
                    sound.Play();
                    comCom(redOn);
                    string errMess = "";
                    string noTaskMess = "";
                    foreach (string item in errorList)
                    {
                        UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                        string tag = ted.Tagid.ToString();
                        errMess = errMess + tag + "\r\n";
                    }
                    if (errorList.Count > 0)
                    {
                        errMess = "锁异常袋号:" + errMess ;
                    }
                    foreach (string item in notTaskList)
                    {
                        UserTool.TagEpcData ted = UserTool.EpcReader.readEpc(HexUtils.strToHexByte(item));
                        string tag = ted.Tagid.ToString();
                        noTaskMess = noTaskMess + tag + "\r\n";
                    }
                    if (notTaskList.Count > 0)
                    {
                        noTaskMess = "不在任务列表中:" + noTaskMess ;
                    }
                    ltScreenInfo.WriteMessage(errMess+ noTaskMess);
                }
                bool flag = NetHelper.PingIpOrDomainName(ServerIP);
                //检查业务机和门架网络状况
                if (flag == false)
                {
                    ltScreenInfo.WriteMessage("业务机未连接，请检查业务机");
                    sound.Play();


                }
                if (faceUseing == true)
                {
                    string[] deviceIpArr = deviceIp.Split(':');
                    foreach (string deviceIps in deviceIpArr)
                    {
                        bool flagDevice = NetHelper.PingIpOrDomainName(deviceIps);
                        if (flagDevice == false)
                        {
                            ltScreenInfo.WriteMessage("栅栏门未连接，请检查栅栏门");
                            sound.Play();

                        }
                    }
                        
                    
                }
                string[] ipArr = ipAll.Split(':');
                for (int i = 0; i < ipArr.Length; i++)
                {
                    string ip = ipArr[i];
                    flag = NetHelper.PingIpOrDomainName(ip);
                    if (flag == false)
                    {

                        ltScreenInfo.WriteMessage(ip + "门架未连接，请检查门架！");
                        sound.Play();
                    }
                }
                if (!socketSatau)
                {
                    LogHelper.Debug("检测到与通讯组件未连接，重新连接");
                    socketSatau = socketClientMJ.conn();
                    if (socketSatau)
                    {
                        LogHelper.Debug("第一次接入自动重启软件");
                        Application.ExitThread();
                        Application.Restart();
                    }
                }
                if (!socketClientMJ.socketConn())
                {
                    ltScreenInfo.WriteMessage( "与通讯组件连接中断，请点击手动接入通讯组件或重启通讯组件");
                }
                if (alarmFlag) 
                {
                    if (yellowFlag)
                    {
                        if (!gateComFlag(yellowOn))
                        {
                            ltScreenInfo.WriteMessage("栅栏门连接中断");
                            sound.Play();
                        }
                    }
                    else 
                    {
                        if (!gateComFlag(yellowOff))
                        {
                            ltScreenInfo.WriteMessage("栅栏门连接中断");
                            sound.Play();
                        }
                    }
                    
                }
                
            }
            catch (Exception ex)
            {
                LogHelper.Debug("网络监测" + ex);
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            if (mustOutSack)
            {
                ltScreenInfo.WriteMessage(mustSackNo);
            }
            else
            {
                ltScreenInfo.WriteMessage("当前业务没有必出箱");
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            Application.ExitThread();
            Application.Restart();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Form2 fff = new Form2(iconPattern);
            fff.ShowDialog();
            if (fff.DialogResult == DialogResult.OK)
            {
                Application.Exit();
            }
           
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            //非业务进出库
            try
            {

                List<StackCode> scList = new List<StackCode>();
                StackCode sc = new StackCode();
                sc.Id = stackCode;
                List<string> list = new List<string>();
                list.Add(stackCode);
                StackCodeList scl = new StackCodeList();
                scl.Code = 163847;


                scl.Stacks = list;



                var serializerSettings = new JsonSerializerSettings
                {
                    // 设置为驼峰命名
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                string json = JsonConvert.SerializeObject(scl, Newtonsoft.Json.Formatting.None, serializerSettings);

                byte[] data = CommondHelper.DataCommit(taskIdSend,sequence, "4002", "11", json, operatorUser, auditorUser);
                socketClientMJ.sendAsynchronous(data);
                flagMJ = false;
                //flagGate = false;
                flagUser = false;

            }
            catch (Exception ex)
            {
                LogHelper.Debug("提交出错" + ex);
            }
        }

        private void button7_Click_1(object sender, EventArgs e)
        {


            comComGate(gateOn);
            Thread.Sleep(gateTime);
            comCom(gateOff);

        }
    
      
        

        private void button11_Click_1(object sender, EventArgs e)
        {
            string contentView = "未扫描袋号\r\n";
            foreach (string str in notScanList)
            {
                contentView = contentView + str + ":";
            }
            ltScreenInfo.WriteMessage(contentView);
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            if (alarmFlag) 
            {
                //任务上传完成
                if (gateFlag) 
                {
                    if (NetHelper.PingIpOrDomainName(gateIP))
                    {
                        string[] ipArr = ipAll.Split(':');
                        for (int i = 0; i < ipArr.Length; i++)
                        {
                            string ip = ipArr[i];
                            if (ip.Length > 5 && !ip.Equals("127.0.0.1"))
                            {
                                turnOnFlag1 = readerMJ.mjTurnOff(ip);
                                LogHelper.Debug("监测门架" + ip + "关闭状态" + turnOnFlag1);
                            }
                        }

                    }
                    else 
                    {
                        string[] ipArr = ipAll.Split(':');
                        for (int i = 0; i < ipArr.Length; i++)
                        {
                            string ip = ipArr[i];
                            if (ip.Length > 5 && !ip.Equals("127.0.0.1"))
                            {
                                turnOnFlag1 = readerMJ.mjTurnOn(ip);
                                LogHelper.Debug("监测门架" + ip + "启动状态" + turnOnFlag1);
                            }
                        }
                    }
                }
                
            }
            
        }

        List<ToDoTask> toDoListOne = new List<ToDoTask>();
        List<ToDoTask> toDoListTwo = new List<ToDoTask>();
        List<ToDoTask> toDoListFinal = new List<ToDoTask>();

        private void button12_Click(object sender, EventArgs e)
        {
            taskList.Reverse();
            executeList.Reverse();
            if (taskList.Count > 0&& executeList.Count>0) 
            {
                foreach (ToDoTask task in taskList)
                {
                    string strs = "联机任务";
                    string id = task.TaskId.Substring(0, 8);
                    string taskIdBin = HexUtils.HexStringToBinString(id).Replace(" ", "");
                    if (taskIdBin.Substring(0, 1).Equals("1")) 
                    {
                        strs = "脱机任务";
                        
                        taskIdBin = "0" + taskIdBin.Substring(1, 31);
                        id = HexUtils.binStringToHexString(taskIdBin);
                        id = id.PadLeft(8, '0');
                        
                    }
                    Console.WriteLine("task.TaskId====" + task.TaskId);
                    string idTen = Convert.ToInt32(id, 16).ToString();
                    string strOne = task.TaskId.Substring(8, task.TaskId.Length - 8);
                    Console.WriteLine(executeList[0] + "==16进制任务==" + id + "==10进制" + idTen);
                  
                    if (executeList[0].Contains(task.TaskId.Substring(1, 7)))
                    {


                        task.TaskId = idTen + strOne + ":缺省任务" + ":" + strs;
                        toDoListOne.Add(task);
                    }
                    else
                    {
                        task.TaskId = idTen + strOne + ":非缺省任务" + ":" + strs;
                        toDoListTwo.Add(task);
                    }

                }
                foreach (ToDoTask task in toDoListOne)
                {
                    toDoListFinal.Add(task);
                }
                foreach (ToDoTask task in toDoListTwo)
                {
                    toDoListFinal.Add(task);
                }
                comboBox1.DataSource = toDoListFinal;
                comboBox1.DisplayMember = "taskId";//显示出来的。Text

                comboBox1.ValueMember = "taskMsg";// value值。
            }
            

        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            Console.WriteLine("下拉框=====" + comboBox1.Text + "----" + comboBox1.SelectedItem + "---" + comboBox1.SelectedText);
            ToDoTask td = (ToDoTask)comboBox1.SelectedItem;
            Console.WriteLine("下拉框=====" + td.TaskId + "----" + td.TaskMsg);
            if (td.TaskId.Contains("不可执行"))
            {
                ltScreenInfo.WriteMessage("当前任务不可执行");
            }
            else 
            {
                if (comboBox1.Text != null)
                {
                    //if (comboBox1.Text.Length == 8)
                    //{
                    string taskStr = Convert.ToString(int.Parse(td.TaskId.Split(':')[0]), 16);
                    if (taskStr.Length == 6) { taskStr = "00" + taskStr; } 
                    else if (taskStr.Length == 7) { taskStr = "0" + taskStr; }
                    else if (taskStr.Length == 5) { taskStr = "000" + taskStr; }
                    else if (taskStr.Length == 4) { taskStr = "0000" + taskStr; }

                    taskIdSend = taskStr;
                    dataToPDAFinal = td.TaskMsg;
                    JObject jo = JObject.Parse(dataToPDAFinal);
                    string code = jo["code"].ToString();
                    LogHelper.Debug("下发code为" + code);
                    string messInfo = "";
                    string messTask = "";
                    epcDataPlan = "";
                    mustOutSack = false;
                    switch (code)
                    {
                        case ("131074"):
                            sackMap.Clear();
                            messInfo = "出库业务，请刷卡开启栅栏门";
                            messTask = "出库业务";
                            //stackCode = ((JArray)jo["stockPackInfoList"])[0]["sstackCode"].ToString();
                            //osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                            osc = (OutScanCMD)JsonConvert.DeserializeObject<OutScanCMD>(dataToPDAFinal);
                            foreach (outScanStockPackInfo ossp in osc.StockPackInfoList)
                            {
                                string sackNo = ossp.SackNo;
                                string voucherTypeID = ossp.VoucherTypeID;
                                string mustOutFlag = ossp.MustOutFlag;
                                epcDataPlan = epcDataPlan + sackNo + ":";
                                sackMap.Add(sackNo, voucherTypeID);
                                if (mustOutFlag.Equals("1"))
                                {
                                    mustOutSack = true;
                                    mustSackNo = mustSackNo + sackNo + ":";
                                }

                            }

                            break;
                        case ("131075"):
                            messInfo = "入库业务，请刷卡开启栅栏门";
                            messTask = "入库业务";
                            //stackCode = ((JArray)jo["stackInfoList"])[0]["sstackCode"].ToString();
                            esc = (EnterScanCMD)JsonConvert.DeserializeObject<EnterScanCMD>(dataToPDAFinal);
                            moneyPlan = 0;
                            notScanList.Clear();
                            //遍历计划内的锁条号和金额
                            foreach (paymentSack ps in esc.PaymentSackList)
                            {
                                string sackNo = ps.SackNo;
                                string sackMoney = ps.SackMoney;
                                moneyPlan = moneyPlan + long.Parse(sackMoney);
                                epcDataPlan = epcDataPlan + sackNo + ":";
                                notScanList.Add(sackNo);
                            }

                            jihua = esc.PaymentSackList.Length;
                            break;
                        case ("131078"):
                            messInfo = "日核对业务，请刷卡开启栅栏门";
                            messTask = "日核对业务";

                            break;
                        case ("131073"):
                            messInfo = "空包袋登记业务，如需进库请刷卡开启栅栏门";
                            messTask = "空包袋登记业务";
                            //sstackCode = ((JArray)jo["stackInfoList"])[0]["sstackCode"].ToString();

                            break;
                        case ("131079"):
                            messInfo = "非业务进出库，请刷卡开启栅栏门";
                            messTask = "非业务进出库";
                            //stackCode = ((JArray)jo["stacks"])[0]["id"].ToString();
                            LogHelper.Debug("库间名称" + stackCode + "意图" + ((JArray)jo["stacks"])[0]["intention"].ToString());
                            messInfo = messInfo + ((JArray)jo["stacks"])[0]["intention"].ToString();
                            NoBusinessCMD nbc = (NoBusinessCMD)JsonConvert.DeserializeObject<NoBusinessCMD>(dataToPDAFinal);
                            string spbccode = nbc.Spbccode;
                            string spbccodeName = nbc.SpbccodeName;
                            string nsumAmt = nbc.NsumAmt;
                            if (nsumAmt != null && nsumAmt != "")
                            {
                                messTask = "无签封出入库业务";
                                messInfo = "无签封出入库业务,任务总金额" + nsumAmt + "请刷卡开启栅栏门";
                            }

                            break;
                        case ("131076"):
                            messTask = "实物交接业务";
                            break;
                        case ("65537"):
                            messInfo = "库内封装业务，请刷卡开启栅栏门";
                            messTask = "库内封装";

                            break;
                        case ("131080"):
                            messInfo = "库内封装业务，请刷卡开启栅栏门";
                            messTask = "库内封装";

                            break;
                    }
                    if (mustOutSack)
                    {
                        messInfo = messInfo + ",当前业务包含必出箱，请优先出必出箱";
                    }
                    ltScreenInfo.WriteMessage(messInfo);

                    LogHelper.Debug("当前业务" + messTask);
                    ltTaskInfo.WriteMessage("当前业务:" + messTask);

                    flagGate = true;

                    bc = new BaseCommand();
                    bc.Code = int.Parse(code);
                    flagMJ = true;

                    epcList.Clear();
                    flagUser = true;
                    errorList.Clear();
                    notTaskList.Clear();
                }
            }
            
            //}
        }
    }
}
